Javascript Function to Update the Query String Value of a URL String


We want to be able to call a javascript function to replace a value with a query string Key. The examples:

1
2
3
4
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'
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:

1
2
updateURL("https://www.example.com/?name=name&age=25", "aaaa", "aaa")
'https://www.example.com/?name=name&age=25&aaaa=aaa'
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 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; 
} 
/**
* 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) —

GD Star Rating
loading...
284 words
Last Post: Teaching Kids Programming - Algorithms to Check if Linked List Strictly Increasing
Next Post: Teaching Kids Programming - Counting Sort Algorithm in Python

The Permanent URL is: Javascript Function to Update the Query String Value of a URL String

Leave a Reply