Posted almost 6 years ago. Visible to the public.

JavaScript: How to generate a regular expression from a string

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

Copy
new RegExp('Hello Universe'); # => /Hello Universe/

You can also use special characters:

Copy
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:

Copy
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:

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

You can now say:

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

Props to bobince on Stack Overflow.

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:

Copy
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").

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
almost 6 years ago
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more