如何更换连续的&符号,使单个&符号保持不变。下面是我尝试过的脚本,它将每个&符号替换为双分号。
<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('&', ";");
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
答案 0 :(得分:4)
最简单的方法是定义一个包含/g
两次的全局正则表达式(带有&
标志):
str.replace(/&&/g, ";"); // replace exactly "&&" anywhere in the string with ";"
运行样本:
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/&&/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(/(&){2}/g, ";")