我的字符串长度不得超过8个字符,例如:
// represented as array to demonstrate multiple examples
var strs = [
'11111111',
'1RBN4',
'12B5'
]
通过函数运行时,我希望所有数字字符加起来以返回最后一个字符串:
var strsAfterFunction = [
'8',
'1RBN4',
'3B5'
]
在这里,您可以看到第一个字符串中的所有8个单个
1
字符最终都成为一个8
字符串,第二个字符串保持不变,因为在任何时候都没有相邻的数字字符,而第三个字符串随着1
和2
字符的变化而变化。 3
,字符串的其余部分保持不变。我相信用伪代码实现此目的的最佳方法是:
1. split the array by regex to find multiple digit characters that are adjacent
2. if an item in the split array contains digits, add them together
3. join the split array items
将
.split
正则表达式拆分成多个相邻的数字字符是什么,例如:var str = '12RB1N1'
=> ['12', 'R', 'B', '1', 'N', '1']
编辑:
问题:
字符串“999”的结果应该是“27”还是“9”呢?
如果很清楚,请始终对数字求和,即
999
=> 27
,234
=> 9
最佳答案
您可以对整个转换执行此操作:
var results = strs.map(function(s){
return s.replace(/\d+/g, function(n){
return n.split('').reduce(function(s,i){ return +i+s }, 0)
})
});
对于您的
strs
数组,它返回["8", "1RBN4", "3B5"]
。关于javascript通过正则表达式拆分字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17051955/