views:

68

answers:

4

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

I want to alter 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 using javascript?

A: 
location.href=location.href.replace(/page=3/,'page=1')
S.Mark
+1  A: 
var s="/admin/editblogentry?page=3&color=blue"
var re=/(.*page=)(\d+)(&.*)*/
s.replace(re,"$11$3")
ghostdog74
+1  A: 

Assuming that the URL contains only one number (i.e. the page numbers), this is the simplest regex:

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

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);
}
TJ