Categories
JavaScript Answers

How to Search and Replace Specific Query String Parameter Value in JavaScript?

Spread the love

To search and replace specific query string parameter value in JavaScript, we can use the URLSearchParams constructor.

For instance, we can write:

const paramsString = "foo=bar";
const searchParams = new URLSearchParams(paramsString);
searchParams.set('foo', 'baz')
const newParamString = searchParams.toString()
console.log(newParamString)

We create a URLSearchParams instance by passing in the paramsString string as its argument.

Then we use the set method from the returned object to replace the value of the foo query parameter with a new value.

We just pass in the key of the value to replace and the value to replace it with.

Finally, we call toString to return the new search parameter string.

Therefore, newParamString is now 'foo=baz' according to the console log.

Conclusion

To search and replace specific query string parameter value in JavaScript, we can use the URLSearchParams constructor.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *