how to add some thing to url by js

Solutions on MaxInterview for how to add some thing to url by js by the best coders in the world

showing results for - "how to add some thing to url by js"
Vladimir
25 Jan 2018
1function insertParam(key, value) {
2    key = encodeURIComponent(key);
3    value = encodeURIComponent(value);
4
5    // kvp looks like ['key1=value1', 'key2=value2', ...]
6    var kvp = document.location.search.substr(1).split('&');
7    let i=0;
8
9    for(; i<kvp.length; i++){
10        if (kvp[i].startsWith(key + '=')) {
11            let pair = kvp[i].split('=');
12            pair[1] = value;
13            kvp[i] = pair.join('=');
14            break;
15        }
16    }
17
18    if(i >= kvp.length){
19        kvp[kvp.length] = [key,value].join('=');
20    }
21
22    // can return this or...
23    let params = kvp.join('&');
24
25    // reload page with new params
26    document.location.search = params;
27}
28