1

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


1 Answer 1

1

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

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

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.