Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

 m@myregex@

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

like image 829
pepper Avatar asked May 02 '14 22:05

pepper


3 Answers

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+");
like image 66
Ryan Avatar answered Oct 24 '22 12:10

Ryan


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

Not really.. you can avoid using any regex delimiter by using new RegExp (string) constructor.

var re = new RegExp (string);

Just keep in mind that this will require you to double escape instead of single escape.

like image 6
anubhava Avatar answered Oct 24 '22 12:10

anubhava


In Javascript, if you want to inline a regexp, your only option is the forwardslash delimiter: /foo/

As other answers note, you can also assign a regular expression to a variable using new Regexp("foo").

Using multiple delimiters is definitely a Perl thing. In Perl you can use nearly any character as a delimiter, for example with strings:

typical syntax using single quotes -- 'dipset'

using the q function -- q(dipset) q!dipset! q%dipset%

Whether this produces something readable is dependent on context.. it's nice that Perl lets you do this, if the result is something that is readable. For example, regular expressions are unreadable enough, without having a bunch of escaped backslashes inside.

like image 5
php_on_rails Avatar answered Oct 24 '22 11:10

php_on_rails