Javascript用正则表达式拆分字符串然后加入它

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

Psi*_*dom 5

您可以为此任务使用regexreplace方法:

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)

  • 您可以在 [此处](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Switching_words_in_a_string) 看到一些示例。 (3认同)