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

1

4 Answers 4

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks.I tried this code but i am getting error Uncaught TypeError: Cannot read property 'get' of undefined
@PrismDevelopmentTeamgroupe Can you show us what you've tried? Or creating a fiddle? As you can see on this page, there is no error like that. So, it should be better if you provide the code.
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);

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.