Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript replace query string value [duplicate]

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&")
like image 904
user1766306 Avatar asked Dec 21 '22 13:12

user1766306


1 Answers

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");
like image 170
ruakh Avatar answered Jan 06 '23 17:01

ruakh