Change Javascript regex URL

I have a URL like /admin/editblogentry?page=3&color=blue

I want to change the "page" in the url to 1 so that the url becomes

/admin/editblogentry?page=1&color=blue

What is the best way to accomplish this with javascript?

+3
source share
4 answers
var s="/admin/editblogentry?page=3&color=blue"
var re=/(.*page=)(\d+)(&.*)*/
s.replace(re,"$11$3")
+1
source

Assuming the URL contains only one number (e.g. page numbers), this is the simplest regular expression:

"/admin/editblogentry?page=3&color=blue".replace(/\d+/, 10001)
+1
source

Another way to do it.

function changePage (url, newPage) {
  var rgx=/([?&]page=)\d+/;
  var retval = url.replace(rgx, "$1" + newPage);
  return retval;
}

var testUrls = [
  "name?page=123&sumstuff=123",
  "/admin/editblogentry?page=3&color=blue",
  "name?foo=bar123&page=123"
];

for (var i=0; i<testUrls.length; i++) {
  var converted = changePage(testUrls[i], i);
  alert(testUrls[i] + "\n" + converted);
}
+1
source
location.href=location.href.replace(/page=3/,'page=1')
0
source

Source: https://habr.com/ru/post/1734990/


All Articles