You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求协助开发实现两种场景的自定义文件编号JavaScript函数

Solution for Updating File Number Suffix

Hey there! I've put together a straightforward JavaScript function that handles both of your required scenarios smoothly. Let's take a look:

The Function

function updateFileNumber(fileno, count) {
  // Regex to match "-数字" at the end of the string
  const numberSuffixRegex = /-(\d+)$/;
  
  if (numberSuffixRegex.test(fileno)) {
    // Replace existing numeric suffix
    return fileno.replace(numberSuffixRegex, `-${count}`);
  } else {
    // Append new numeric suffix
    return `${fileno}-${count}`;
  }
}

How It Works

Let's break down what's happening here:

  • Regex Matching: The regex /-(\d+)$/ targets a - followed by one or more digits only at the end of the string. This ensures we don't accidentally modify -数字 sequences that appear in the middle of your filename.
  • Scenario 1 (No Existing Suffix): If the regex doesn't find a match, we simply append -${count} to the original string.
  • Scenario 2 (Existing Suffix): If a match is found, we replace the entire -数字 suffix with -${count} to update the number.

Test Examples

Here are some quick tests to verify it works as expected:

// Case 1: No existing suffix
let fileno1 = 'test';
let c1 = 4;
console.log(updateFileNumber(fileno1, c1)); // Output: 'test-4'

// Case 2: Existing suffix to replace
let fileno2 = 'report-7';
let c2 = 12;
console.log(updateFileNumber(fileno2, c2)); // Output: 'report-12'

// Edge case: String has dashes but no trailing number
let fileno3 = 'project-alpha';
let c3 = 2;
console.log(updateFileNumber(fileno3, c3)); // Output: 'project-alpha-2'

// Edge case: String has middle dashes with numbers
let fileno4 = 'invoice-2024-3';
let c4 = 5;
console.log(updateFileNumber(fileno4, c4)); // Output: 'invoice-2024-5'

内容的提问来源于stack exchange,提问作者BobbyJones

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:48:17