4

Possible Duplicate:
add or update query string parameter

I am trying to replace the page number in the query string no matter what digit is to 1.

query string

index.php?list&page=2&sort=epub

javascript

window.location.href.replace(new RegExp("/page=.*?&/"), "page=1&")
Community
  • 1
  • 1
user1766306
  • 117
  • 2
  • 8

1 Answers1

11

Your code looks almost right; however:

  • you need to use either new RegExp or the special // regex syntax, but not both.
  • the replace method doesn't modify the string in-place, it merely returns a modified copy.
  • rather than .*?, I think it makes more sense to write \d+; more-precise regexes are generally less likely to go awry in cases you haven't thought of.

So, putting it together:

window.location.href = window.location.href.replace(/page=\d+/, "page=1");
ruakh
  • 156,364
  • 23
  • 244
  • 282