Parsing URLs and Retrieving Query Parameters in JavaScript

Javascript
2017-03-02 14:50 (7 years ago) ytyng

The code new URL(location.href).searchParams.get('q') is a JavaScript expression used to retrieve the value of the query parameter q from the current page's URL. Here is a step-by-step breakdown of what this code does:

  1. location.href gets the full URL of the current page.
  2. new URL(location.href) creates a new URL object using the current page's URL.
  3. .searchParams accesses the URLSearchParams object associated with the URL, which allows you to work with the query string of the URL.
  4. .get('q') retrieves the value of the query parameter named q from the URL's query string.

For example, if the current page's URL is https://example.com/page?q=searchterm, executing this code will return the string "searchterm".

Currently unrated

Comments

Archive

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011