Getting a regular expression from a string in JavaScript is quite simple:
new RegExp('Hello Universe');
# => /Hello Universe/
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
").