We want to be able to call a javascript function to replace a value with a query string Key. The examples:
updateURL("https://www.example.com/?name=name&age=25", "name", "hello")
'https://www.example.com/?name=hello&age=25'
updateURL("https://www.example.com/?name=name&age=25", "age", 12)
'https://www.example.com/?name=name&age=12'
If the query key is not existent, we should add/append one:
updateURL("https://www.example.com/?name=name&age=25", "aaaa", "aaa")
'https://www.example.com/?name=name&age=25&aaaa=aaa'
URL Query String Key/Value Update with a Javascript Function
The following is the Javascript function that allows us to easily update the query parameters in a URL and also append one if the key parameter (URL query parameters) is not existent in the original URL string.
/**
* Parameter url: the input URL to change
* Parameter arg: the querystring key to change
* Parameter val: the value to update
* Return: the updated URL
*/
function updateURL(url, arg, val) {
const text = arg + '=' + val;
const pattern = arg + '=([^&]*)';
if (url.match(pattern)){
let tmp = '/(' + arg + '=)([^&]*)/gi';
tmp = url.replace(eval(tmp), text);
return tmp;
} else if (url.match('[\?]')) {
return url + '&' + text;
}
return url + '?' + text;
}
–EOF (The Ultimate Computing & Technology Blog) —
267 wordsLast Post: Teaching Kids Programming - Algorithms to Check if Linked List Strictly Increasing
Next Post: Teaching Kids Programming - Counting Sort Algorithm in Python