[英]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('&', ";");
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
The simplest way would be to define a global regex (with a /g
flag) that contains &
最简单的方法是定义一个包含
&
的全局正则表达式(带有/g
标志) &
twice: 两次:
str.replace(/&&/g, ";"); // replace exactly "&&" anywhere in the string with ";"
Running sample: 运行样本:
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>
or use a {min,max}
regex pattern as Alex R specified 或使用
{min,max}
正则表达式模式指定Alex R
您需要在regex语句中使用{min [,max]}修饰符:
str.replace(/(&){2}/g, ";")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.