簡體   English   中英

Javascript用正則表達式分割字符串,然后將其加入

[英]Javascript split string with regex and then join it

嘿,我想要一個可以分割字符串的函數,例如"(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

您可以使用regexreplace方法來完成此任務:

 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) ) 

看起來vars數組填充了空結果,這些結果無意間加了“ 1”。 我稍微修改了箭頭功能,以檢查x的值。

vars = vars.map(x=>{
    if (x) {
       return x+"1";
    }
});

可以簡化一點(但是\\w匹配下划線[a-zA-Z0-9_] ):

 console.log( '(12/x+3)*heyo'.replace(/\\w+/g, '$&1') ) console.log( '(12/x+3)*heyo'.replace(/\\w+/g, m => m + 1) ) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM