0

Am getting string like this for example

var names = "(Ajar,Sentinel,Manor,),(Dagwood,Steve,Guru,)";

I need output like this

(Ajar,Sentinel,Manor),(Dagwood,Chateau,Guru)

When I use

names.replace(",)",")");

It is replacing only the first ",)"

Suhaib Janjua
  • 3,538
  • 16
  • 59
  • 73
  • Possible duplicate of [How to replace all occurrences of a string in JavaScript?](http://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – Sergey Shubin Apr 04 '17 at 09:29

1 Answers1

0

for replacing all occurrence of a string, you should use regular expressions. Example https://davidwalsh.name/javascript-replace

Or for temporary solution you can use



<p id="demo">My Output</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
 var names = "(Ajar,Sentinel,Manor,),(Dagwood,Steve,Guru,)";
    var res = names.replace(",)", ")").replace(",)", ")");
    document.getElementById("demo").innerHTML = res;
}
</script>

For all Purpose Following code is working fine



function myFunction() {
 var names = "(Ajar,Sentinel,Manor,),(Dagwood,Steve,Guru,),(a,b,c,),(p,q,r,),(dfg,)";

    var res = names.replace(/\,\)/g,')');
    document.getElementById("demo").innerHTML = res;
}

Anil sikhwal
  • 1
  • 1
  • 4