最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replace only occuring in first element - Stack Overflow

programmeradmin5浏览0评论

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
Add a ment  | 

5 Answers 5

Reset to default 6

Use 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]') );
发布评论

评论列表(0)

  1. 暂无评论