Reputation: 1101
I would like to know how to replace the param in the url using javascript without regex.
for example,
I need to change param value amt=100
to amt=2000
of url using javascript.
url1 ="www.xyz.com?src=service&amt=100&day=10"
url2="www.xyz.com?src=service&amt=200&day=10"
function changeUrl(url, newamt){
var newurl= location.split("=")[1].replace(newamt);
return newurl
}
changeUrl(url1, 2000);
changeUrl(url2, 1500);
Expected Output:
www.xyz.com?src=service&amt=2000&day=10
www.xyz.com?src=service&amt=1500&day=10
Upvotes: 1
Views: 101
Reputation: 1716
You can use the below function to do so.
function changeUrl(url, newamt){
var href = new URL(url);
href.searchParams.set('amt', newamt);
return href.toString();
}
console.log(changeUrl("https://www.example.com?src=service&amt=100&day=10", 2000));
console.log(changeUrl("https://www.example.com?src=service&amt=200&day=10", 1500));
Upvotes: 1