请求协助开发实现两种场景的自定义文件编号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
相关产品推荐
相关产品推荐

