1

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?

1 Answer 1

2

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.

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

2 Comments

My wording was a bit ambiguous. I don't to match (34 variable) but (34) variable. Therefore I used var re = new RegExp('^\\(\\d+\\) ' + variable);. Thanks for your help in solving this :)
@Michael: Good, I updated the answer and also added more on the subject.

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.