JavaScript字符串相邻奇数加'-'时末尾多出短横线的问题
The issue occurs because when the loop reaches the last character (i = str.length -1), str[i+1] is undefined. In JavaScript, undefined % 2 returns NaN, and NaN !== 0 evaluates to true. So if the last character is odd, your condition passes and appends an unnecessary dash.
Solution 1: Adjust the Condition in the Loop
Add a check to ensure we only look ahead if there's a next character (i.e., i < str.length -1):
const str = "999463" const numberWithDash = [] for (let i = 0; i < str.length; i++) { // Only add dash if current is odd, there's a next character, and next is also odd if (str[i] % 2 !== 0 && i < str.length - 1 && str[i + 1] % 2 !== 0) { numberWithDash.push(str[i] + '-') } else { numberWithDash.push(str[i]) } }; console.log(numberWithDash.join('')) // Output: "9-9-9463"
Solution 2: Use Regular Expression (Concise Approach)
A regex can handle this in one line by matching odd numbers followed by another odd number, and inserting a dash between them:
const str = "999463" const result = str.replace(/([13579])(?=[13579])/g, "$1-") console.log(result) // Output: "9-9-9463"
The regex ([13579])(?=[13579]) uses a positive lookahead to find any odd number followed by another odd number, then replaces the match with the first number plus a dash.
内容的提问来源于stack exchange,提问作者Richard B.

