我有一些 javascript 代码可以创建一个包含字符和整数的变量。
我需要将此字符串中的连续整数相加,同时不影响其他单个或后续连续整数。
假设我的输入是
GhT111r1y11rt
我需要我的输出是:
GhT3r1y2rt
我该怎么做?
最佳答案
使用String#replace
带有回调和内部回调的方法使用 String#split
计算总和和 Array#reduce
方法。
console.log(
'GhT111r1y11rt'.replace(/\d{2,}/g, function(m) { // get all digit combination, contains more than one digit
return m.split('').reduce(function(sum, v) { // split into individual digit
return sum + Number(v) // parse and add to sum
}, 0) // set initial value as 0 (sum)
})
)
\d{2,}
匹配 2 个或更多重复的数字,这比 \d+
更好,因为我们不想替换单个数字。
关于javascript - 在字符串中添加多个连续的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42070190/