Dhay
Dhay

Reputation: 621

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>

Upvotes: 2

Views: 1818

Answers (2)

nem035
nem035

Reputation: 35501

The simplest way would be to define a global regex (with a /g flag) that contains &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

Upvotes: 4

Alex R
Alex R

Reputation: 624

You need the {min[,max]} modifier in your regex statement:

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

Upvotes: 2

Related Questions