How to extract the query string from the URL in javascript?
Thank you!
A query string is part of the full query, or URL, which allows us to send information using parameters as key-value pairs.
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.
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.
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>; };
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"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With