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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)