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.c
Solution 1:
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
.
functionurlGenerator (key, value) {
let temp = '(?<='+`${key}`+'=)[^&]+'let reg = newRegExp(temp,'g');
console.log(reg);
var url = "www.domain.com/?id=10&name=xxx&dob=2018-12-13";
// change the value for given keyreturn 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);
Solution 2:
I use replace
to change value by regex.
Try this urlGenerator
function :
functionurlGenerator(url, field, value) {
var reg = newRegExp('('+field+'=[^&]*)', "");
return url.replace(reg, field+'='+value);
}
EDIT:
If you wan't a static url in your function :
functionurlGenerator(field, value) {
var url = "www.domain.com/?id=10&name=xxx&dob=2018-12-13";
var reg = newRegExp('('+field+'=[^&]*)', "");
return url.replace(reg, field+'='+value);
}
Post a Comment for "Change Query Parameters Of Url Using Dynamic Parameter And Value In Jquery"