Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the query string by javascript?

How to extract the query string from the URL in javascript?

Thank you!

like image 980
Jayesh Avatar asked May 25 '10 18:05

Jayesh


People also ask

What is query string in JavaScript?

A query string is part of the full query, or URL, which allows us to send information using parameters as key-value pairs.

How do I pass query string?

To pass in parameter values, simply append them to the query string at the end of the base URL. In the above example, the view parameter script name is viewParameter1.

Which JavaScript statement can you use to retrieve a query string from the current Web page's URL and assign it to the queryString variable?

You can simply use URLSearchParams() . Lets see we have a page with url: https://example.com/?product=1&category=game. On that page, you can get the query string using window.

How do I get query string in react?

Get a single Query String value location.search object: import React from 'react'; import { useSearchParams } from 'react-router-dom'; const Users = () => { const [searchParams] = useSearchParams(); console. log(searchParams); // ▶ URLSearchParams {} return <div>Users</div>; };


1 Answers

You can easily build a dictionary style collection...

function getQueryStrings() {    var assoc  = {};   var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };   var queryString = location.search.substring(1);    var keyValues = queryString.split('&');     for(var i in keyValues) {      var key = keyValues[i].split('=');     if (key.length > 1) {       assoc[decode(key[0])] = decode(key[1]);     }   }     return assoc;  }  

And use it like this...

var qs = getQueryStrings(); var myParam = qs["myParam"];  
like image 145
Josh Stodola Avatar answered Sep 29 '22 01:09

Josh Stodola