Categories
JavaScript Answers

How to append a param onto the current URL with JavaScript?

Spread the love

Sometimes, we want to append a param onto the current URL with JavaScript.

In this article, we’ll look at how to append a param onto the current URL with JavaScript.

How to append a param onto the current URL with JavaScript?

To append a param onto the current URL with JavaScript, we can create a new URL instance from the URL string.

Then we can call the searchParams.append method on the URL instance to append a new URL parameter into it.

For instance, we write:

const url = new URL("http://foo.bar/?x=1&y=2");
url.searchParams.append('z', 42);
const newUrl = url.toString();
console.log(newUrl)

to create a new URL instance with "http://foo.bar/?x=1&y=2".

Then we call url.searchParams.append with the URL param key and value respectively.

And then we call toString to return the new URL string.

Therefore, newUrl is 'http://foo.bar/?x=1&y=2&z=42'.

Conclusion

To append a param onto the current URL with JavaScript, we can create a new URL instance from the URL string.

Then we can call the searchParams.append method on the URL instance to append a new URL parameter into it.

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 *