Dwa*_*fri 1 javascript regex split
嘿,我想要一个可以拆分字符串的函数,例如"(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;
}
Run Code Online (Sandbox Code Playgroud)
例如:(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)
)Run Code Online (Sandbox Code Playgroud)
根据您要匹配的字符,您可能需要/([^-+/*()]+)/g作为模式:
var s = "(12/x+3)*heyo";
console.log(
s.replace(/([^-+/*()]+)/g, "$1" + 1)
)Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
992 次 |
| 最近记录: |