我将拥有一个长度不超过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