JavaScript正则表达式将连续的与号符号替换为分号

javascript regex replace sequential ampersand symbol to semicolon

本文关键字:符号 替换 正则表达式 连续 JavaScript      更新时间:2023-09-26

如何替换连续的与号,保持单和号不变。下面是我尝试过的脚本,它将每个与号替换为双分号。

<html>
<body>
<p id="demo">Women->Lingerie & Sleepwear->Bras&& Women->Western Wear->Shorts & Capris&& Women->Lingerie & Sleepwear->Nightwear & Nighties</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML; 
    var res = str.replace('&amp', ";");
    document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>

最简单的方法是定义一个包含两次&amp;的全局正则表达式(带有 /g 标志):

str.replace(/&amp;&amp;/g, ";"); // replace exactly "&amp;&amp;" anywhere in the string with ";"

运行示例:

function myFunction() {
  var str = document.getElementById("demo").innerHTML;
  var res = str.replace(/&amp;&amp;/g, ";");
  document.getElementById("demo").innerHTML = res;
}
<p id="demo">
  Women->Lingerie & Sleepwear->Bras&& Women->Western Wear->Shorts & Capris&& Women->Lingerie & Sleepwear->Nightwear & Nighties</p>
<button onclick="myFunction()">Try it</button>

或使用 Alex R 指定的{min,max}正则表达式模式

你需要正则表达式语句中的 {min[,max]} 修饰符:

str.replace(/(&amp;){2}/g, ";")