DEV Community

Ian Felix
Ian Felix

Posted on

2 1

How to get query params from a URL in JavaScript

Use the property searchParams from URL interface to get the query params from a URL.

Examples:

In the following example, we have a URL with name and lastname as query params.

const url = new URL('https://example.com/path?name=Ian&lastname=Felix');

// using method get from searchParams

const name = url.searchParams.get('name');
const lastName = url.searchParams.get('lastname');

console.log(name); // 'Ian'
console.log(lastName); // 'Felix'

const myName = `${name} ${lastName}`;

console.log(myName); // 'Ian Felix' - this is my name :)
Enter fullscreen mode Exit fullscreen mode

We can use some methods from the searchParams to help us to handle with the query params.

Methods:

Below is a list of some methods from the searchParams property.

URL.searchParams.get();
// returns the value of the first query parameter with the given name

URL.searchParams.getAll();
// returns an array of all query parameters with the given name

URL.searchParams.has();
// returns true if the given query parameter exists

URL.searchParams.set();
// sets the value of the first query parameter with the given name
Enter fullscreen mode Exit fullscreen mode

You can find more information about interfaces and type aliases in the official TypeScript documentation. - MDN Docs

Thank you for reading this article.
If you enjoy this article, please upvote and comment.
Follow me on Twitter

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay