pepper
pepper

Reputation: 2197

JavaScript regex delimiters - how to not escape any 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@

So, in Perl, to match a string that contains the string /tmp, this is a valid regex, without any escape and very readable:

 m@/tmp@

Instead in JavaScript, it seems I need to write /\/tmp/ or something like that. Are we confined to always escape "/" in JavaScript?

Upvotes: 25

Views: 13223

Answers (3)

Ryan
Ryan

Reputation: 14649

The short answer is No. JavaScript does not offer a native way to express a custom regex delimiter.

In the simple way of using regular expressions in JavaScript you would delimit it with / /. However, also using the native constructor of RegExp, that accepts a string as first argument, you also need to escape slashes, and twice.

The following examples are equivalent to match a string containing the value /tmp:

// shortway, you must escape any internal '/' as '\/'
// note that you cannot change the delimiter
var re = /\/tmp/;

// constructor, you must escape any '/' twice as '\\/'
// note that you cannot express a delimiter
var re = new RegExp('\\/tmp');

So, in native JavaScript, regexes must have slashes escaped.

Upvotes: 17

php_on_rails
php_on_rails

Reputation: 319

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.

Upvotes: 6

anubhava
anubhava

Reputation: 785196

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.

Upvotes: 8

Related Questions