Can someone help on why this is only replacing the '[m]' in the first LI? The rest of them stay as '[m]'
aData[2] = "<li>1[m]</li><li>2[m]</li><li>3[m]</li>"
$.html( aData[2].replace('[m]','[media]') )
Can someone help on why this is only replacing the '[m]' in the first LI? The rest of them stay as '[m]'
aData[2] = "<li>1[m]</li><li>2[m]</li><li>3[m]</li>"
$.html( aData[2].replace('[m]','[media]') )
Share
Improve this question
edited Aug 17, 2012 at 1:10
Brock Adams
93.7k23 gold badges241 silver badges305 bronze badges
asked Feb 6, 2012 at 20:46
Control FreakControl Freak
13.2k31 gold badges99 silver badges150 bronze badges
5 Answers
Reset to default 6Use a regular expression and make it global:
$.html( aData[2].replace(/\[m\]/g,'[media]') )
you need to use a regular expression to replace all in javascript, in this case it would be
$.html( aData[2].replace(/\[m\]/g,'[media]') )
Javascripts replace
method only replaces the first matched item unless you use a regular expression:
http://davidwalsh.name/javascript-replace
Use a regular expression literal, /[m]/
, instead of letting the string '[m]'
get implicitly converted to a regular expression. That way you can add the /g
("replace all") flag:
$.html( aData[2].replace(/[m]/g,'[media]') )
though I should add that you actually want \[m\]
rather than [m]
, so that you match the literal square-brackets:
$.html( aData[2].replace(/\[m\]/g,'[media]') )
You need to make it a global replace.
var mre = new RegExp( "[m]", "g" );
aData[2] = "<li>1[m]</li><li>2[m]</li><li>3[m]</li>";
$.html( aData[2].replace(mre,'[media]') );