Home  >  Q&A  >  body text

JavaScript: Does the RegExp.escape function exist?

I just want to create a regular expression with any possible string.

var usersString = "Hello?!*`~World()[]";
var expression = new RegExp(RegExp.escape(usersString))
var matches = "Hello".match(expression);

Is there a built-in method? If not, what do people use? Ruby has RegExp.escape. I feel like I don't need to write my own, there must be some standard.

P粉381463780P粉381463780338 days ago742

reply all(2)I'll reply

  • P粉662089521

    P粉6620895212023-11-17 17:07:41

    For anyone using Lodash, As of v3.0.0 the _.escapeRegExp function is built-in:

    _.escapeRegExp('[lodash](https://lodash.com/)');
    // → '\[lodash\]\(https:\/\/lodash\.com\/\)'

    And, if you don't want to need the full Lodash library, you may want That's it!

    reply
    0
  • P粉734486718

    P粉7344867182023-11-17 14:43:25

    The functionality linked in the other answer is insufficient. It cannot escape ^ or $ (beginning and end of string) or -, which are used in character groups for ranges. < /p>

    Use this function:

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

    Although it may seem unnecessary at first glance, escaping - (as well as ^) makes this function also suitable for escaping characters to be inserted into character classes as regular expressions the subject.

    Escapes / Makes this function suitable for escaping characters to be used in JavaScript regular expression literals for later evaluation.

    Since there is no harm in escaping any of them, it makes sense to escape to cover a wider range of use cases.

    Yes, disappointingly, this is not part of standard JavaScript.

    reply
    0
  • Cancelreply