Javascript用正则表达式replace替换父串中所有符合条件的子串

这样用,只会替换匹配到的第一个子串

str = 'I hava a pen ,I hava an apple,apple pen, pen apple'
str = str.replace('apple', 'pear')   
//str='I hava a pen ,I hava an pear,apple pen, pen apple'

  

加上全局标识(g),替换全部子串

str = 'I hava a pen ,I hava an apple,apple pen, pen apple'
str = str.replace(/apple/g, 'pear')   
//str='I hava a pen ,I hava an pear,pear pen, pen pear'

  

如果子串中有特殊字符,那么需要转义:
/static\/article_img/g
/static\.article_img/g

  




posted @ 2018-04-18 17:34  961897  阅读(392)  评论(0编辑  收藏  举报