![](/img/trans.png)
[英]JavaScript How can I replace a char from a String with 2 new chars
[英]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 (.*)
.
*
!
我自己發現的答案是:
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.