1

My code is as follows:

var regex = new RegExp ('(.*/*)');
console.log(regex);

I think the result is:

/(.*/*)/

But the actual result is:

/(.*\/*)/

Could someone please explain this for me?

2 Answers 2

1

The leading and trailing forward slashes are just how JavaScript represents a regex in string form and as a literal. The mean the same thing:

var regex = new RegExp ('(.*/*)');

is the same as

var regex = /(.*\/*)/;

It is important to escape the middle / otherwise it would interpret it as the end of the literal.

Sign up to request clarification or add additional context in comments.

3 Comments

Sorry, how to have output is /(.*/*)/ if i want to use constructor of RegExp
@ThiepLV that would be invalid. why do you want it that way?
Because i want to match a pattern is more any character then /* or any other string
0

If you expect the last asterisk * to be literal you need to escape it, otherwise it's a quantifier in regex meaning "match between zero and unlimited times". It's also recommened to escape the forward slash /, even if it might work without doing so.

(.*\/\*)

If you want to match any string /* any string then use:

(.*\/\*.*)

https://regex101.com/r/aJ4eA4/1

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.