Replace function only works once (javascript)

后端 未结 1 646
伪装坚强ぢ
伪装坚强ぢ 2021-02-07 20:11

I need to replace a string (str1) with another string (str2) every time str1 shows in a specific div.

This is what I got so far



        
相关标签:
1条回答
  • 2021-02-07 20:33

    Use regex /string/g to replace all occurrences, you are using substring which will replace only first occurances as per documentation of replace() function.

    Live Demo

    var n=str.replace(/Google/g,"Yahoo");
    

    String.prototype.replace() The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

    str.replace(regexp|substr, newSubStr|function)

    You are using substr pattern which will replace first occurance only.

    substr (pattern)

    A String that is to be replaced by newSubStr. It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.

    Use this regexp patter to replace all occurances.

    regexp (pattern)

    A RegExp object or literal. The match is replaced by the return value of parameter #2.

    0 讨论(0)
提交回复
热议问题