Javascript - how to replace a sub-string?

后端 未结 4 2106
长情又很酷
长情又很酷 2021-02-19 16:37

This is a simple one. I want to replace a sub-string with another sub-string on client-side using Javascript.

Original string is \'original READ ONLY\'

4条回答
  •  不知归路
    2021-02-19 17:34

    String.replace() is regexp-based; if you pass in a string as the first argument, the regexp made from it will not include the ‘g’ (global) flag. This option is essential if you want to replace all occurances of the search string (which is usually what you want).

    An alternative non-regexp idiom for simple global string replace is:

    function string_replace(haystack, find, sub) {
        return haystack.split(find).join(sub);
    }
    

    This is preferable where the find string may contain characters that have an unwanted special meaning in regexps.

    Anyhow, either method is fine for the example in the question.

提交回复
热议问题