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