javascript正则表达式将顺序&符号替换为分号

时间:2016-03-12 04:31:02

标签: javascript regex

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

<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>

2 个答案:

答案 0 :(得分:4)

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

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>

或使用{min,max}正则表达式作为Alex R specified

答案 1 :(得分:2)

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

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