Replacement occurs only in the first element

Can someone help why this only replaces "[m]" in the first LI? The rest remain "[m]"

aData[2] = "<li>1[m]</li><li>2[m]</li><li>3[m]</li>" $.html( aData[2].replace('[m]','[media]') ) 
+4
source share
5 answers

Use a regex and make it global:

 $.html( aData[2].replace(/\[m\]/g,'[media]') ) 
+6
source

you need to use regex to replace all in javascript, in which case it will be

 $.html( aData[2].replace(/\[m\]/g,'[media]') ) 
+4
source

The Javascripts replace method replaces only the first matching element if you are not using a regular expression:

http://davidwalsh.name/javascript-replace

+1
source

Use the regular expression literal, /[m]/ , instead of letting the string '[m]' get implicitly converted to the regular expression. This way you can add the /g flag ("replace all"):

  $.html( aData[2].replace(/[m]/g,'[media]') ) 

although I have to add that you really want \[m\] , not [m] , so that you match literal square brackets:

  $.html( aData[2].replace(/\[m\]/g,'[media]') ) 
+1
source

You need to make a global replacement.

 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]') ); 
0
source

Source: https://habr.com/ru/post/1395086/


All Articles