Reputation: 621
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>
Upvotes: 2
Views: 1818
Reputation: 35501
The simplest way would be to define a global regex (with a /g
flag) that contains &
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
Upvotes: 4
Reputation: 624
You need the {min[,max]} modifier in your regex statement:
str.replace(/(&){2}/g, ";")
Upvotes: 2