pepper pepper - 1 year ago 81
Javascript Question

Javascript regex delimiters (any alternative to forward slash)?

Is there any way in Javascript to use a different character than

(forward slash) as a delimiter in a regular expression?
Most other languages have a way of doing this.

For example, Perl:


Are we confined to just using "/" in Javascript?

Answer Source

In the simple way of using regular expressions in JavaScript you would delimit it with the / character. However, if you would like to use the global object RegExp, then you would need to pass in a string as the first argument to the constructor using the normal string escape rules. The following are equivalent.

// shorthand way.
var re = /\w+/;
// a way to pass a string in
var re = new RegExp("\\w+");