Changing url parameter with javascript.
Saturday, July 4th, 2009Here is a url. “http://localhost/service?page=2”. What I want to do is to add ‘per_page’ parameter to the url. If I can convince that the url does not have ‘per_page’ parameter, itt’s easy. just add the ‘&per_page=20’ to the end of url. But there are several patterns in url, and I want to handle all the cases well.
The patterns are like belows.
1. http://localhost/service 2. http://localhost/service?page=2 3. http://localhost/service?per_page=2 4. http://localhost/service?page=2&per_page=10 5. http://localhost/service?per_page=10&page=2 6. http://localhost/service?page=2&per_page=10&sort=name
1. No parameter,
2. per_page does not exist,
3. only per_page exists,
4. per_page is at the end,
5. per_page is at the first,
6. per_page is in the middle.
After a couple of hours of consideration, I decided to use a regular expression. My strategy is simple. Remove per_page param first, and then add per_page param.
function update_param(url, value) {
return url.replace(/per_page=\d+&?/, "")+"&per_page="+value;
}
Very simple. It searches ‘per_page=xxx’ or ‘per_page=xxx&’ pattern from url and remove it. And then add per_page param to the end. But it’s not working for every case, unforunately. It does not return the good result for case 1 and 3. And it assumes that the value of per_page is number.
My final solution is the below.
function update_param(url, name, value) {
host = url.split("?")[0];
params = url.split("?")[1] || "";
var re1 = new RegExp(name + '=.+&');
var re2 = new RegExp(name + '=.+');
params = params.replace(re1, "").replace(re2, "").replace(/&$/, "")+"&"+name+"="+value;
params = params.replace(/^&/, "");
return host + "?" + params;
}
Now it works for every cases. Moreover, it receives param name as a parameter, and it does not assume the value’s type. But more complicated than before.
I am using regular expressions more and more nowdays. Even though It seemed very difficult for the first time, I’ve come to know it wonderful, as I’ve studied more and more. My final solution does not seem to be good. It’s too complicated. Let me konw your opinion to make it better.