0

How can a string be replaced in Javascript with regex ?

A particular regular expression is bugging me right now. I simply want to replace the count=15 in a string like:

countryNo=-1&count=15&page=2

How can I get a format like given below:

countryNo=-1&count=**20**&page=2

Or

countryNo=-1&count=**30**&page=2

I have tried the following:

var x = 'countryNo=-1&count=15&page=2';
x = x.replace('count=\d{2}', 'count=30');

Nothing happens. How can I make it work?

3 Answers 3

6

Use a regex literal, not a string literal:

x = x.replace(/count=\d{2}/, 'count=30');

Reference: MDN on regular expressions

As an aside, you could be DRYer, you don't have to repeat "count=":

x = x.replace(/(count=)\d{2}/, '$130');
Sign up to request clarification or add additional context in comments.

3 Comments

For completness sake, could you explain DRYer (edit)cheers!
@Neurofluxation It means "more DRY", with DRY being an acronym for "Don't Repeat Yourself", which is an important principle for maintainable coding.
You know... Programming since I was 10 or 11 and never heard the acronym DRY. I've heard Don't Repeat Yourself a lot, but never DRY. Here, have an upvote!
0

You're specifying your regular expression as a string. Use:

x = x.replace(/count=\d{2}/, 'count=30');

Comments

0

Remove the Regex from the string literal

try following

x = x.replace(/count=\d{2}/, 'count=30');

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.