How do I do global string replace without needing to escape everything?

前端 未结 4 620
不思量自难忘°
不思量自难忘° 2021-01-23 21:02

I want to replace all occurences of a pattern in a string by another string. For example, lets convert all \"$\" to \"!\":

\"$$$\" -> \"!!!\"
<
4条回答
  •  滥情空心
    2021-01-23 21:34

    There is no standard regexp escape function in Javascript.

    You can write your own (source) or get it from your library (dojo example)

    function escape(s) {
        return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
    };
    

    This allows us to create the custom regex object at runtime

    function replace_all(string, pattern, replacement){
        return string.replace( new RegExp(escape(pattern), "g"), replacement);
    }
    

提交回复
热议问题