-1

Possible Duplicate:
Fastest method to replace all instances of a character in a string

I have this

<p id="demo">/,\,:,*,?,",<,>,|</p>
<input type="button" onclick="myFunction()" value="Replace"/>

function myFunction() {
    var str = document.getElementById("demo").innerHTML;
    var n = str.replace(",", ", ");
    document.getElementById("demo").innerHTML = n;
}

What I want is to replace this "/,\,:,*,?,",<,>,|" with this "/, \, :, *, ?, ", <, >, |" but what I get is this "/, \,:,*,?,",<,>,|".

What am I doing wrong ??

Community
  • 1
  • 1
yogi
  • 19,175
  • 13
  • 62
  • 92
  • You find answer here: http://stackoverflow.com/questions/6064956/replace-all-occurrences-in-a-string – Baptiste Pernet Oct 04 '12 at 08:28
  • Or here: http://stackoverflow.com/questions/2116558/fastest-method-to-replace-all-instances-of-a-character-in-a-string -- So obviously a duplicate amoung lots of other topics about the same problem. – w00 Oct 04 '12 at 08:31

3 Answers3

2

You'll have to use a regex to replace the string globally:

var n = str.replace(/,/g, ', ');
Blender
  • 289,723
  • 53
  • 439
  • 496
1

Replace this line var n = str.replace(",", ", ");

with

var n = str.replace(/,/g, ", ");

Default it only will replace the first occurens

Simon Edström
  • 6,461
  • 7
  • 32
  • 52
0

The replace in javascript replaces only the first occurrence.

You need do use either regex, or a loop.

Check this out : Javascript multiple replace

Community
  • 1
  • 1
arpad
  • 541
  • 5
  • 10