Javascript string.replace with regex
I want to replace a url querystring parameter with a new value if it already exists or add it on if not.
e.g.
The current url could be:
a.www.mysite.com/whatever.asp?page=5&version=1
OR
b. www.mysite.com/whatever.asp?version=1
I need the resulting url to be www.mysite.com/whatever.asp?page=1&version=1
I suspect I can use string.replace with a regex t开发者_如何学Co do this the most intelligent way but am hoping for a little help with it from someone more experienced with regexs :) Thanks!
I would rather use location.search
along with some .splits()
and Array.prototype.some
help.
var s = location.search.slice(1).split(/&/);
check = s.some(function(elem) {
return elem.split(/=/)[0] === 'page';
});
if(!check) s.push('page=1');
location.href = location.hostname + location.pathname + '?' + s.join('&');
I think the clearest solution would be to write one regex that parses the URL, and then build a URL from there. Here's what I would do:
function urlCleanup(url) {
var match = /http:\/\/www\.mysite\.com\/whatever.asp\?(page=(\d+))?&?(version=(\d+))?/.exec(url);
var page = match[2] ? match[2] : "0";
var version = match[4] ? match[4] : "0";
return "http://www.mysite.com/whatever.asp?page=" + page + "&version=" + version;
}
var testUrls = [ "http://www.mysite.com/whatever.asp?page=4"
, "http://www.mysite.com/whatever.asp?version=5"
, "http://www.mysite.com/whatever.asp?page=4&version=5" ];
for(i in testUrls)
console.log(urlCleanup(testUrls[i]));
One problem this doesn't handle is having the variables in the opposite order in the url (e.g. ?version=5&page=2
). To handle that, it would probably make more sense to use two regexes to search the URL for each parameter, like this:
function urlCleanup(url) {
var match, page, version;
match = /version=(\d+)/.exec(url);
version = match ? match[1] : "0";
match = /page=(\d+)/.exec(url);
page = match ? match[1] : "0";
return "http://www.mysite.com/whatever.asp?page=" + page + "&version=" + version;
}
var testUrls = [ "http://www.mysite.com/whatever.asp?page=4"
, "http://www.mysite.com/whatever.asp?version=5"
, "http://www.mysite.com/whatever.asp?version=5&page=2"
, "http://www.mysite.com/whatever.asp?page=4&version=5" ];
for(i in testUrls)
console.log(urlCleanup(testUrls[i]));
精彩评论