从https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_replace2获取
现在我想更改字符串中的+91。来自 https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_replace2
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "blue" with "red" in the paragraph below:</p>
<p id="demo">Mr Blue has a blue house and a blue car.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/blue/g, "red");
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
让我们考虑以下字符串。
字符串:-嗨,我的号码是 +919090909090 和 +9190820209282 等等。
我想要的结果如下:嗨,我的号码是 +91 - 9090909090 和 +91 - 90820209282 等等。
但是当我使用正则表达式模式时,似乎在使用时出现错误
str.replace(/blue/g, "red");
Invalid regular expression: /+91/: Nothing to repeat"
最佳答案
+
符号是正则表达式中的特殊字符
Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) (from regex101.com)
如果你想匹配字符串文字+
,则需要对其进行转义:
/\+91/
将匹配。
像您希望的那样的示例替换是(再次来自 regex101.com )
const regex = /(\+91)/g;
const str = `+911147005555, +911147005556, +919999973703`;
const subst = `\$1 - `;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
关于javascript - 如何使用正则表达式模式替换+91?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42413906/