javascript - 如何使用正则表达式模式替换+91?

标签 javascript html regex pattern-matching

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/

相关文章:

javascript - 动态创建没有字符串的引用

html - 流动宽度(最小宽度)侧边栏,内容占据其余宽度

regex -\w 和\b 正则表达式元字符之间的区别

.net - 用于生成正则表达式的最终用户工具

html - Firefox/Safari 设置高度为 [specified height - padding - border] for input[type=button]

node.js - 如何制作一个遍历所有 .m 和 .h 文件并替换这行代码的脚本

javascript - 找出多个数组中的差异。使用减少

javascript - EmberJS Action - 当包装在 `actions` 中时从另一个 Action 调用一个 Action

javascript - 我想在一定时间后自动淡入 div onclick 和淡出 div

javascript - 获取点击链接的值