Friday, 18 November 2016

javascript - Change query parameters of URL using dynamic parameter and value in jQuery




I need to change the value of query parameters of the given URL irrespective of value type.



I have a function like,



function urlGenerator (key, value) {
var url = "www.domain.com/?id=10&name=xxx&dob=2018-12-13";
// change the value for given key
return url;
}



The order of query parameters are not fixed. It may be of any order. I think the solution can be found by Regex.



I need generic solution irrespective of the type of value given to above specified URL. I need to call the above method like following and must get the resultant URL.



result = urlGenerator('id', 15);
result = urlGenerator('name', 'yyy');
result = urlGenerator('dob', '2018-10-20');



Thanks in advance!!


Answer



You can do it like this



So here in temp variable we are building a expression for regex using string template and than using RegExp change it to regex object.And then by using replace method we replace the matched value with the value supplied in function.





function urlGenerator (key, value) {
let temp = '(?<='+`${key}`+'=)[^&]+'

let reg = new RegExp(temp,'g');
console.log(reg);
var url = "www.domain.com/?id=10&name=xxx&dob=2018-12-13";
// change the value for given key
return url.replace(reg, value);
}

result = urlGenerator('id', 15);
console.log(result);
result = urlGenerator('name', 'yyy');

console.log(result);
result = urlGenerator('dob', '2018-10-20');
console.log(result);




No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...