2

How to replace url query string values using javascript

I have url like

xyz.com?src=a&dest=b

I want to replace a=c and b=d

and final url will be

xyz.com?src=c&dest=d

  • Please check if this helps https://stackoverflow.com/questions/13275421/javascript-replace-query-string-value – Tinu Jos K Jan 14 '20 at 05:10

4 Answers4

5

Maybe you're looking for something like this:

var url = new URL('https://example.com?src=a&dest=b');

var src = url.searchParams.get('src');
var dest = url.searchParams.get('dest');

console.log('current src:', src);
console.log('current dest:', dest);

var search_params = new URLSearchParams(url.search); 

search_params.set('src', 'c');
search_params.set('dest', 'd');

url.search = search_params.toString();

var new_url = url.toString();

console.log(new_url);
Tân
  • 1
  • 15
  • 56
  • 102
  • Thanks.I tried this code but i am getting error Uncaught TypeError: Cannot read property 'get' of undefined – Prism Development Team group e Jan 14 '20 at 05:56
  • 1
    @PrismDevelopmentTeamgroupe Can you show us what you've tried? Or creating a [fiddle](https://jsfiddle.net/)? As you can see on this page, there is no error like that. So, it should be better if you provide the code. – Tân Jan 14 '20 at 06:00
0

You can just use String.prototype.replace, like:

let myString = "xyz.com?src=a&dest=b";
myString = myString.replace("=a","=c");
myString = myString.replace("=b","=d");
console.log(myString);
Cat
  • 4,141
  • 2
  • 10
  • 18
0

Follow this:

const urlObject = new URL(url);
const id = urlObject.searchParams.get('id')
console.log(id)

It helps you to take the parameters and then :

new URLSearchParams(url)

using this you can create your new parameters.

Mahdi
  • 206
  • 2
  • 14
0

Below is the pure js(ES5) code to do the job.

function updateSearchParams() {
        var searchStr = window.location.search,
            resultSearchArray = [], resultSearchStr;
        var searchParamsStr =  searchStr.split('?')[1];
        var searchParamsArray = searchParamsStr.split('&');
        for(var searchIter = 0; searchIter < searchParamsArray.length; searchIter++) {
            var searchParam = searchParamsArray[searchIter];
            var searchParamKey = searchParam.split('=')[0];
            var searchParamValue = searchParam.split('=')[1];
            // Below modification is just an example - Ideally the below string check should be via constants declared
            if(searchParamKey === 'src') {
                searchParamValue = 'c'
            } else if(searchParamKey === 'dest') {
                searchParamValue = 'd';
            }
            resultSearchStr = searchParamKey + '=' + searchParamValue;
            resultSearchArray.push(resultSearchStr);
        }
        window.location.search = '?' + resultSearchArray.join('&');
    }

Just call this function and it should work.