1

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?

10
  • 3
    why would you ever inspect regex.source? Commented Oct 10, 2013 at 3:46
  • I'm carrying out some project that's sensitive to punctuations. Commented Oct 10, 2013 at 3:49
  • 3
    I don't understand what you mean by generating a string by creating a regex and inspecting its source property. The regex is created with a string, so if you have the string already, what is the source property lookup going to buy you? Commented Oct 10, 2013 at 3:50
  • I don't think what you're asking for is possible, and I definitely feel like you're abusing regex for something it wasn't meant for. Commented Oct 10, 2013 at 3:52
  • The point is that it returns a string without using quotation marks. Commented Oct 10, 2013 at 3:57

1 Answer 1

3

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\/';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.