Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

regex - Which characters to escape when using RegExp object in JavaScript?

I have the regex ^(d+) which is designed to match parentheses containing digits and which does what is expected.

I want to extend this to match digits in parentheses followed by a space followed by a string which comes from a variable. I know that I can crate a RegExp object to do this but am having trouble understanding which characters to escape to get this to work. Is anybody able to explain this to me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you do not use RegEx, you can use a literal notation:

/^(d+)/

But when you are using the RegEx constructor, you need to double escape these symbols:

var re = new RegExp("^\(\d+\)");

MDN Reference:

There are 2 ways to create a RegExp object: a literal notation and a constructor. To indicate strings, the parameters to the literal notation do not use quotation marks while the parameters to the constructor function do use quotation marks.

... Use literal notation when the regular expression will remain constant.

... Use the constructor function when you know the regular expression pattern will > be changing, or you don't know the pattern and are getting it from another source, such as user input.

Now, in case you have a variable, it is a good idea to stick to the constructor method.

var re = new RegExp('^\(\d+\) ' + variable);

Escaping the slash is obligatory as it is itself is an escaping symbol.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...