嘿,我想要一个可以拆分字符串的函数,例如 "(12/x+3)*heyo"
我可以单独编辑每个数字、字母和单词,然后返回编辑后的内容版本。到目前为止,我得到了这个(它没有按预期工作):
function calculate(input){
var vars = input.split(/[+-/*()]/);
var operations = input.split(/[^+-/*()]/);
var output = "";
vars = vars.map(x=>{
return x+"1";
});
for(var i=0; i<operations.length; i++){
output += operations[i]+""+((vars[i])?vars[i]:"");
}
return output;
}
例如:(12/x+3)*heyo
返回:(1121/x1+31)*1heyo1
但应该返回 (121/x1 +31)*heyo1
最佳答案
您可以使用regex
和replace
方法来完成此任务:
var s = "(12/x+3)*heyo";
console.log(
s.replace(/([a-zA-Z0-9]+)/g, "$1" + 1)
)
根据您要匹配的字符,您可能需要 /([^-+/*()]+)/g
作为模式:
var s = "(12/x+3)*heyo";
console.log(
s.replace(/([^-+/*()]+)/g, "$1" + 1)
)
关于Javascript 使用正则表达式拆分字符串,然后加入它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47559629/