How to replace several words in javascript

前端 未结 6 807
心在旅途
心在旅途 2020-12-06 07:43

I wanna replace several words in a text using replace() in javascript, how can I do that?

For example, if I wanna replace, \'Dave Chambers,

6条回答
  •  悲&欢浪女
    2020-12-06 08:09

    Use a regular expression with the alternator (|) and case insensitive modifier (/i):

    var str = sometext.innerHTML,
        reg = /Dave Chambers|David Chambers|Will Smith/i;
    
    str = str.replace(reg, "Jackie Chan"); 
    

    A shorter, more complex regex could be:

    /Dav(?:e|id) Chambers|Will Smith/i;
    

    And if there may be more than 1 occurrence, add the global modifier (g) to replace all:

    /Dav(?:e|id) Chambers|Will Smith/ig;
    

    You can learn more about regular expressions here, or by searching Google. You can see a working demo here.

提交回复
热议问题