簡體   English   中英

JavaScript-如何將某些字符替換為函數中的字符串

[英]JavaScript - How can I replace string with certain char in to a function

我該如何使用正則表達式,用!替換每個字符串! 包裝功能:

例子:

  • 3! => fact(3)

  • 2.321! => fact(2.321)

  • (3.2+1)! => fact(3.2+1)

  • (sqrt(2)+2/2^2)! => fact(sqrt(2)+2/2^2)

根據您的示例,您根本不需要正則表達式:

var s = "3!"; //for example

if (s[s.length-1] === "!")
    s = "fact(" + s.substr(0, s.length-1) + ")";

對於最后一種情況,括號不加倍僅需要另一個測試:

var s = "(sqrt(2)+2/2^2)!"; //for example

if (s[s.length-1] === "!") {
    if(s.length > 1 && s[0] === "(" && s[s.length-2] === ")") 
        s = "fact" + s.substr(0, s.length-1);
    else
        s = "fact(" + s.substr(0, s.length-1) + ")";
}
var testArr =  [];
testArr.push("3!");
testArr.push("2.321!");
testArr.push("(3.2+1)!");
testArr.push("(sqrt(2)+2/2^2)!");

//Have some fun with the name. Why not?
function ohIsThatAFact(str) {
    if (str.slice(-1)==="!") {
         str = str.replace("!","");
         if(str[0]==="(" && str.slice(-1)===")") 
             str = "fact"+str;
         else 
             str = "fact("+str+")";
    }
    return str;
}

for (var i = 0; i < testArr.length; i++) {
    var testCase = ohIsThatAFact(testArr[i]);
    document.write(testCase + "<br />");
}

小提琴的例子

"(sqrt(2)+2/2^2)!".replace(/(.*)!/g, "fact($1)");

擺弄吧!

(.*)!

  • 匹配下面的正則表達式,並將其匹配捕獲到反向引用編號1 (.*)

    • 匹配不是換行符的任何單個字符.
    • 在0到無限制的時間之間,盡可能多次,並根據需要進行回饋(貪婪) *
  • 從字面上匹配字符“!” !

我自己發現的答案是:

Number.prototype.fact = function(n) {return fact(this,2)}
str = str.replace(/[\d|\d.\d]+/g, function(n) {return "(" + n + ")"}).replace(/\!/g, ".fact()")

但我會看看其他答案是否會好得多,以為它們是

這是根據操作要求; 使用正則表達式:

"3*(2+1)!".replace(/([1-9\.\(\)\*\+\^\-]+)/igm,"fact($1)");

您可能會以雙括號結尾:

"(2+1)!".replace(/([1-9\.\(\)\*\+\^\-]+)/igm,"fact($1)");

暫無
暫無

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

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