MattBianco
MattBianco

Reputation: 1531

Quoting regex literals in javascript? Why not?

In this answer to a question, and lots of other places, I see unquoted strings in javascript.

For example:

var re = /\[media id="?(\d+)"?\]/gi;

Why shouldn't it instead be:

var re = '/\[media id="?(\d+)"?\]/gi';

Is it some kind of special handling of regular expressions, or can any string be declared like that?

Upvotes: 1

Views: 113

Answers (4)

F.P
F.P

Reputation: 17831

Because, in JavaScript, Regex is a built-in type, not a string-pattern that is passed to some parser like e.g. in C# or Java.

That means that when you write var regex = /pattern/, JavaScript automatically uses that literal as a regular expression pattern, making regex an object of the RegExp type.

See: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

Upvotes: 2

Adam Mihalcin
Adam Mihalcin

Reputation: 14458

Is it some kind of special handling of regular expressions?

Yes, regular expressions get special handling. As MDN points out, there is a built-in JavaScript regular expression type, with its own syntax for literals.

or can any string be declared like that?

No. Since regular expressions are objects and are not strings, if you tried to write a string with a regular expression literal you would get a regular expression object, not a string.

Upvotes: 1

Tom
Tom

Reputation: 4180

it's only for regular expressions, not for strings.

Upvotes: 2

xdazz
xdazz

Reputation: 160863

var re = /\[media id="?(\d+)"?\]/gi;

is regex literal, not a string.

Upvotes: 3

Related Questions