How to properly escape characters in regexp

后端 未结 4 1831
失恋的感觉
失恋的感觉 2020-11-30 08:59

I want to do a string search inside a string. Simply saying MySTR.search(Needle).

The problem occurs when this needle string contains speci

4条回答
  •  生来不讨喜
    2020-11-30 09:33

    Duplicate of https://stackoverflow.com/a/6969486/151312

    This is proper as per MDN (see explanation in post above):

    function escapeRegExp(str) {
      return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    }
    

提交回复
热议问题