Reputation: 2067
I'm using the following Javascript to generate a String: /abc/.source
.
By running this code in console, it will return "abc"
.
Now I want to generate a string like "abc/"
.
I tried /abc\//.source
but it returns "abc\/"
.
How can I achieve this WITHOUT using var reg = new RegExp("abc/");reg.source
?
Upvotes: 1
Views: 305
Reputation: 147403
I think you misunderstand the source property:
Let S be a String in the form of a Pattern equivalent to P, in which certain characters are escaped as described below. S may or may not be identical to P or pattern; however, the internal procedure that would result from evaluating S as a Pattern must behave identically to the internal procedure given by the constructed object's [[Match]] internal property.
15.10.4.1 new RegExp(pattern, flags)
In other words, the source value must be able to be used as the string in a regular expression constructor:
var re = new RegExp( s.source );
Where the resulting expression must behave the same as the original when used in match.
So given that to match 'abc/' the required pattern is abc\/
then /abc\//.source
must be abc\/
.
And BTW:
(new RegExp('abc/')).source == 'abc\/';
Upvotes: 3