开发者

Javascript regular expression URL alteration

开发者 https://www.devze.com 2022-12-21 11:02 出处:网络
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

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&开发者_如何学Python;color=blue

What is the best way to accomplish this using javascript?


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


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)


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


location.href=location.href.replace(/page=3/,'page=1')
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号