0

I have a string that contains a value that looks like this.

somevalueshere=123&page=3&someothervalues=123

and I want to replace the number 3 with 1. So it would look like page=1

The number is always a positive whole number like 1,2,3,4,5,6,7

All I have so far is

.replace("page=" + 'some number reg ex here', "page=1")
4
  • yes, sorry I updated my post Commented Jan 11, 2017 at 22:38
  • 1
    Possible duplicate of Using javascript replace to replace numbers in a string? Commented Jan 11, 2017 at 22:41
  • 1
    @MikeMcCaughan That doesn't look for a pattern before the number, it just replaces the number anywhere. Commented Jan 11, 2017 at 22:51
  • So, the question is, do we want users to have to think or not? Or learn regex rather than coming back to SO every time? Apparently not. How about stackoverflow.com/q/1090948/215552? That will let them change any part of the query string they want. Commented Jan 11, 2017 at 23:08

1 Answer 1

3

The regular expression for a number (without decimals) is \d+. \d matches any numeric digit, and + means at least one of the preceding pattern.

str = str.replace(/\bpage=\d+/, 'page=1');

This is very basic regular expression syntax. If you don't already know it, you should read the tutorial at http://www.regular-expression.info.

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

7 Comments

Could you please explain the regex before I upvote it
@Barmar, really? You couldn't find a dupe for this? Do you really need more rep? :P
@MikeMcCaughan Sometimes it's easier to write a simple answer than go searching for things like this. The search terms tend to be too generic.
@MikeMcCaughan This isn't a generic forum. Please take your salt elsewhere
@CarlMarkham This isn't a help site. We're compiling a library of high-quality questions and answers, not collection of duplicate questions.
|

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.