Read more

JavaScript: How to generate a regular expression from a string

Arne Hartherz
April 30, 2013Software engineer at makandra GmbH

Getting a regular expression from a string in JavaScript is quite simple:

new RegExp('Hello Universe');
# => /Hello Universe/
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

You can also use special characters:

new RegExp('^(\\d+) users')
# => /^(\d+) users/

Our expression above now works only at the beginning of the matched string, looks for a number (\d+ [1]) and also captures that. Sweet.

However, mind that your input will not be magically escaped because of that:

new RegExp('makandra.com')
# => /makandra.com/

The above expression would match "makandra.com" but also "makandra-com" or "makandraxcom".

Regexp.escape

If you need special characters in strings to be escaped (to avoid the above issue), there is no built-in method -- you can add one, however:

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

You can now say:

var hostname = 'makandra.com';
new RegExp(RegExp.escape(hostname));
# => /makandra\.com/

Props to bobince on Stack Overflow Show archive.org snapshot .

How to add switches

When you construct a new RegExp you can't add switches (like i, g, etc.) to the expression from the string. Simply pass them as a second argument:

new RegExp('foo', 'i');
# => /foo/i

[1] Note that we need to say "\\d" in our string when we want our string to contain "\d" (just because backslashes always need to be escaped in strings unless you mean an escape sequence like "\n").

Posted by Arne Hartherz to makandra dev (2013-04-30 10:04)