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

JavaScript字符串相邻奇数加'-'时末尾多出短横线的问题

Fix for Extra Dash at End of Number String

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.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 02:05:18