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?
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+");
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With