How to Easily Manipulate Search Queries in JavaScript

How to Easily Manipulate Search Queries in JavaScript

Ferenc Almasi β€’ 2020 August 11 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

You don't have to write your own custom functions anymore to work with query string, JavaScript has the URLSearchParams API which lets you interact and manipulate search queries with ease.

Copied to clipboard! Playground
// Use the URLSearchParams API to manipulate search queries:
const urlParams = new URLSearchParams(window.location.search);

console.log(urlParams.has('id'));                  // returns true
console.log(urlParams.get('min-price'));           // returns β€œ0”
console.log(urlParams.append('max-price', '999')); // Returns β€œ999”

console.log(urlParams.toString()) // Returns β€œid=123&min-price=0&max-price=999”
query-strings.js

So how well is it supported? According to caniuse.com, global support sits around ~95% at the writing of this article, with IE being unsupported.

Global support of URLSearchParams as shown on caniuse.com

This means, if you need to cater for IE, you also need a fallback option. There is a polyfill for everything on NPMJS.

If you don't want to use a polyfill, but rather implement your own solution, there's also a URL API which has a slightly better support. It supports IE down to version 10.

Copied to clipboard! Playground
const url = new URL(window.location.href);
const searchParams = url.searchParams;

console.log(searchParams.has('id'));                  // returns true
console.log(searchParams.get('min-price'));           // returns β€œ0”
console.log(searchParams.append('max-price', '999')); // Returns β€œ999”
url.js
How to Easily Manipulate Search Queries in JavaScript
If you would like to see more Webtips, follow @flowforfrank

Resource

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.