3

Possible Duplicate:
Why does javascript replace only first instance when using replace?

I have this variable

var newRow = "<td><div> [[myvar]]</div> <div> [[myvar]]</div> </td> "

When i do this

newRow  = newRow.replace('[[myvar]]', '10');

Only first occurance gets replaced and not the second

Community
  • 1
  • 1
Mirage
  • 30,868
  • 62
  • 166
  • 261
  • See [this][1] answer. That is almost the same question. [1]: http://stackoverflow.com/questions/1967119/why-does-javascript-replace-only-first-instance-when-using-replace – David Oct 11 '12 at 08:13

2 Answers2

9

You might use a regular expression

newRow  = newRow.replace(/\[\[myvar\]\]/g, '10');

There is no other simple solution for multiple replacements. Note that :

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • i don't understood , if i have exact match , why do i need to have regex. i mean function replace is same why regex works but not simple string – Mirage Oct 11 '12 at 08:18
  • In Javascript the replace function is actually based on regex. By default the replace hits only the first occurrance. The `g` flag set the global match option. – Alberto De Caro Oct 11 '12 at 08:21
  • thanks buddy. i don't know when i see regex , i heart starts pumping faster like i saw tiger in front of me – Mirage Oct 11 '12 at 08:22
0

Use this:

newRow = newRow.replace(new RegExp('[[myvar]]', 'g'), '10');
techfoobar
  • 65,616
  • 14
  • 114
  • 135