Reputation: 1531
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
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
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
Reputation: 160863
var re = /\[media id="?(\d+)"?\]/gi;
is regex literal, not a string.
Upvotes: 3