简体   繁体   English

javascript正则表达式将连续的&符号替换为分号

[英]javascript regex replace sequential ampersand symbol to semicolon

How to replace sequential ampersand symbol leaving single ampersand untouched. 如何替换连续的&符号,使单个&符号保持不变。 Below is the script I tried which replaces every ampersand into double semicolon. 下面是我尝试的脚本,该脚本将每个“&”号替换为双分号。

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

The simplest way would be to define a global regex (with a /g flag) that contains &amp; 最简单的方法是定义一个包含&amp;的全局正则表达式(带有/g标志) &amp; twice: 两次:

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

Running sample: 运行样本:

 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> 

or use a {min,max} regex pattern as Alex R specified 或使用{min,max}正则表达式模式指定Alex R

您需要在regex语句中使用{min [,max]}修饰符:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM