Get query string parameters url values with jQuery / Javascript (querystring) - javascript

Anyone know of a good way to write a jQuery extension to handle query string parameters? I basically want to extend the jQuery magic ($) function so I can do something like this:
$('?search').val();
Which would give me the value "test" in the following URL: http://www.example.com/index.php?search=test.
I've seen a lot of functions that can do this in jQuery and Javascript, but I actually want to extend jQuery to work exactly as it is shown above. I'm not looking for a jQuery plugin, I'm looking for an extension to the jQuery method.

After years of ugly string parsing, there's a better way: URLSearchParams Let's have a look at how we can use this new API to get values from the location!
//Assuming URL has "?post=1234&action=edit"
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?
post=1234&action=edit&active=1"
UPDATE : IE is not supported
use this function from an answer below instead of URLSearchParams
$.urlParam = function (name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)')
.exec(window.location.search);
return (results !== null) ? results[1] || 0 : false;
}
console.log($.urlParam('action')); //edit

Why extend jQuery? What would be the benefit of extending jQuery vs just having a global function?
function qs(key) {
key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)"));
return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}
http://jsfiddle.net/gilly3/sgxcL/
An alternative approach would be to parse the entire query string and store the values in an object for later use. This approach doesn't require a regular expression and extends the window.location object (but, could just as easily use a global variable):
location.queryString = {};
location.search.substr(1).split("&").forEach(function (pair) {
if (pair === "") return;
var parts = pair.split("=");
location.queryString[parts[0]] = parts[1] &&
decodeURIComponent(parts[1].replace(/\+/g, " "));
});
http://jsfiddle.net/gilly3/YnCeu/
This version also makes use of Array.forEach(), which is unavailable natively in IE7 and IE8. It can be added by using the implementation at MDN, or you can use jQuery's $.each() instead.

JQuery jQuery-URL-Parser plugin do the same job, for example to retrieve the value of search query string param, you can use
$.url().param('search');
This library is not actively maintained. As suggested by the author of the same plugin, you can use URI.js.
Or you can use js-url instead. Its quite similar to the one below.
So you can access the query param like $.url('?search')

Found this gem from our friends over at SitePoint.
https://www.sitepoint.com/url-parameters-jquery/.
Using PURE jQuery. I just used this and it worked. Tweaked it a bit for example sake.
//URL is http://www.example.com/mypage?ref=registration&email=bobo#example.com
$.urlParam = function (name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)')
.exec(window.location.search);
return (results !== null) ? results[1] || 0 : false;
}
console.log($.urlParam('ref')); //registration
console.log($.urlParam('email')); //bobo#example.com
Use as you will.

This isn't my code sample, but I've used it in the past.
//First Add this to extend jQuery
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
//Second call with this:
// Get object of URL parameters
var allVars = $.getUrlVars();
// Getting URL var by its name
var byName = $.getUrlVar('name');

I wrote a little function where you only have to parse the name of the query parameter. So if you have: ?Project=12&Mode=200&date=2013-05-27 and you want the 'Mode' parameter you only have to parse the 'Mode' name into the function:
function getParameterByName( name ){
var regexS = "[\\?&]"+name+"=([^&#]*)",
regex = new RegExp( regexS ),
results = regex.exec( window.location.search );
if( results == null ){
return "";
} else{
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
}
// example caller:
var result = getParameterByName('Mode');

Building on #Rob Neild's answer above, here is a pure JS adaptation that returns a simple object of decoded query string params (no %20's, etc).
function parseQueryString () {
var parsedParameters = {},
uriParameters = location.search.substr(1).split('&');
for (var i = 0; i < uriParameters.length; i++) {
var parameter = uriParameters[i].split('=');
parsedParameters[parameter[0]] = decodeURIComponent(parameter[1]);
}
return parsedParameters;
}

function parseQueryString(queryString) {
if (!queryString) {
return false;
}
let queries = queryString.split("&"), params = {}, temp;
for (let i = 0, l = queries.length; i < l; i++) {
temp = queries[i].split('=');
if (temp[1] !== '') {
params[temp[0]] = temp[1];
}
}
return params;
}
I use this.

Written in Vanilla Javascript
//Get URL
var loc = window.location.href;
console.log(loc);
var index = loc.indexOf("?");
console.log(loc.substr(index+1));
var splitted = loc.substr(index+1).split('&');
console.log(splitted);
var paramObj = [];
for(var i=0;i<splitted.length;i++){
var params = splitted[i].split('=');
var key = params[0];
var value = params[1];
var obj = {
[key] : value
};
paramObj.push(obj);
}
console.log(paramObj);
//Loop through paramObj to get all the params in query string.

function getQueryStringValue(uri, key) {
var regEx = new RegExp("[\\?&]" + key + "=([^&#]*)");
var matches = uri.match(regEx);
return matches == null ? null : matches[1];
}
function testQueryString(){
var uri = document.getElementById("uri").value;
var searchKey = document.getElementById("searchKey").value;
var result = getQueryStringValue(uri, searchKey);
document.getElementById("result").value = result;
}
<input type="text" id="uri" placeholder="Uri"/>
<input type="text" id="searchKey" placeholder="Search Key"/>
<Button onclick="testQueryString()">Run</Button><br/>
<input type="text" id="result" disabled placeholder="Result"/>

Related

Jquery - how to get & consider only 1 URL Parameter and ignore the others?

On my shop i have a filter. When a filter is selected it adds "filter.p.tag=xxx" parameter to the url. Since i have no other possibility to display current active filters, i need to grab them from the URL. And output them under the h1 and update in realtime when a new filter is selected.
For example the URL:
collections/all?filter.p.tag=animal&filter.p.tag=glitter&fbclid=2123&paramblabla=123123
-actually i only want everything after (filter.p.tag) - so in this example under the H1 Heading there should be following:
"Animal & Glitter"
I want to ignore every other parameter without "jquery remove or replace" them since this is unwanted.
THE QUESTION IS: How am i able to only consider the filter.p.tag param and ignore all others?
Now i have this code:
<script>
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function removeDuplicates(arr) {
return arr.filter((item,
index) => arr.indexOf(item) === index);
}
jQuery( document ).ready(function( $ ) {
jQuery(document.body).on('click', ".label_filter", function(){
setTimeout(function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[1]);
// vars[hash[0]] = hash[1];
}
var unqvars = removeDuplicates(vars);
var result = '';
for(var i = 1; i <= unqvars.length; i++){
if(i == unqvars.length){
var sept = '';
}else{
var sept = ' & ';
}
result = unqvars+ sept;
}
var replaced = result.replaceAll(',', ' & ');
var replaced1 = replaced.replaceAll('+', ' ');
var replaced2 = replaced1.replaceAll('-', ' ');
var replaced3 = replaced2.replaceAll('& Page=', ' Seite ');
jQuery('#categoryfromfilter').text(replaced3);
}, 1000);
});
});
</script>
```
Less code, more robust
URLSearchParams().getAll() works well when there are multiple values for the same key name.
However, additional code is needed to make the function handle a wide range of input. For example, here we first parse the query string from the url. URLSearchParams would fail if the path were passed, e.g., /somepath?key=value. Query string values might also be encoded and so decodeURIComponent() is applied to each value.
const getParam = (url, key) =>
new URLSearchParams(url?.toString().split("?").pop())
.getAll(key).map(value => decodeURIComponent(value));
Example:
let url = "/collections/all?filter.p.tag=animals&filter.p.tag=glitter",
key = "filter.p.tag",
result = getParam(url, key);
// Output: "animals,glitter"
Update
OP asked for additional code to pull the filter values from window.location.href. We can use this href to create a URL and then modify the original solution to use URL.searchParams.
Additionally, OP wants to retrieve the filters whenever the page query string changes. This most likely happens when the user clicks a filter option that causes the page to reload with new data. For this we can use the DOMContentLoaded event to check for new filters when the page loads. While less likely, the page might also use History.pushState() to update the query string and for that we could use the popstate event.
function onQueryChange() {
let key = "filter.p.tag";
let url = new URL(window.location.href);
let filters = url.searchParams.getAll(key)
.map(value => decodeURIComponent(value))
.join("&");
// do something with the filters...
}
document.addEventListener("DOMContentLoaded", onQueryChange);
// document.addEventListener("popstate", onQueryChange);
Snippet
Code snippet that displays a range of test values.
const getParam = (url, key) =>
new URLSearchParams(url?.toString().split("?").pop())
.getAll(key).map(value => decodeURIComponent(value));
// Test Values
let name = "filter.p.tag";
["/collections/all?filter.p.tag=animals",
"/collections/all?filter.p.tag=animals&filter.p.tag=glitter",
"/collections/all?fbclid=IwAR2didTPblablabla&filter.p.tag=animals",
"/collections/all?filter.p.tag=animals&fbclid=IwAR2didTPblablabla&filter.p.tag=glitter",
"/collections/all?sort_by=apes&filter.p.tag=animals&fbclid=IwAR2didTPblablabla",
"fbclid=IwAR2didTPblablabla&filter.p.tag=animals",
"filter.p.tag=animals&filter.p.tag=glitter&fbclid=IwAR2didTPblablabla",
"/collections/all?fbclid=IwAR2didTPblablabla",
"filter.p.tag&fbclid=IwAR2didTPblablabla",
"/collections/all",
null,
undefined
].forEach(url => stdout.innerHTML += (`Returns "${getParam(url, name)}" for "${url}"\n`));
<xmp id="stdout"></xmp>

Javascript get URL parameter that starts with a specific string

With javascript, I'd like to return any url parameter(s) that start with Loc- as an array. Is there a regex that would return this, or an option to get all url parameters, then loop through the results?
Example: www.domain.com/?Loc-chicago=test
If two are present in the url, I need to get both, such as:
www.domain.com/?Loc-chicago=test&Loc-seattle=test2
You can use window.location.search to get all parameters after (and including ?) from url. Then it's just a matter of looping through each parameter to check if it match.
Not sure what kind of array you expect for result but here is very rough and basic example to output only matched values in array:
var query = window.location.search.substring(1);
var qsvars = query.split("&");
var matched = qsvars.filter(function(qsvar){return qsvar.substring(0,4) === 'Loc-'});
matched.map(function(match){ return match.split("=")[1]})
Use URLSearchparams
The URLSearchParams interface defines utility methods to work with the
query string of a URL.
var url = new URL("http://" + "www.domain.com/?Loc-chicago=test&NotLoc=test1&Loc-seattle=test2");
var paramsString = url.search;
var searchParams = new URLSearchParams(paramsString);
for (var key of searchParams.keys()) {
if (key.startsWith("Loc-")) {
console.log(key, searchParams.get(key));
}
}
Here is a function you can use that accepts a parameter for what you are looking for the parameter to start with:
function getUrlParameters(var matchVal) {
var vars = [];
var qstring = window.location.search;
if (qstring) {
var items = qstring.slice(1).split('&');
for (var i = 0; i < items.length; i++) {
var parmset = items[i].split('=');
if(parmset[0].startsWith(matchVal)
vars[parmset[0]] = parmset[1];
}
}
return vars;
}

How to find url parameter # with value in javascript

I need to find url parameter # with value in javascript.
my url is like:
http://rohitazad.com/wealth/tax/how-to-file-your-income-tax-return/newslist/34343443.cms?intenttarget=no&utm_source=newsletter&utm_medium=email&utm_campaign=ETwealth&type=wealth#sid53239948&ncode=23432kjk#%kjimwer
i want to find this value #sid53239948
I find this How can I get query string values in JavaScript?
but how to find this value in url?
EDIT:
This will filter the sid into the sid-variable wherever you put your hash.
var url_arr = window.location.hash.split('&'),
sid = '';
url_arr.filter(function(a, b) {
var tmp_arr = a.split('#')
for (var i in tmp_arr)
if (tmp_arr[i].substring(0, 3) == 'sid')
sid = tmp_arr[i].substring(3, tmp_arr[i].length)
});
console.log(sid) // Will output '53239948'
Old answer:
var hash_array = window.location.hash.split('#');
hash_array.splice(0, 1);
console.log(hash_array);
use this plugin that help you to find exact information
https://github.com/allmarkedup/purl
Try this way,
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
// console.log(window.location.href);
// console.log(hashes);
for(var index = 0; index < hashes.length; index++)
{
var hash = hashes[index].split('=');
var value=hash[1];
console.log(value);
}
http://www.w3schools.com/jsref/jsref_indexof.asp
Search a string for "welcome":
var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");
The result of n will be:13. Maybe this helps you. In the posted link in your question you see how you get the url. But be careful: indexOf only returns the 1st occurence.
The post you have referenced is looking for a URL parameter in a string. These are indicated by:
?{param_name}={param_value}
What you are looking for is the anchor part of the URL or the hash.
There is a simple Javascript function for this:
window.location.hash
Will return:
#sid53239948
See reference:
http://www.w3schools.com/jsref/prop_loc_hash.asp
However, given a URL that has multiple hashes (like you one you provided), you will need to then parse the output of this function to get the multiple values. For that you will need to split the output:
var hashValue = window.location.hash.substr(1);
var hashParts = hashValue.split("#");
This will return:
['sid53239948', '%kjimwer']
Since you have hash values in query params, window.location.hash will not work for you. You can try to create an object of query parameters and then loop over them and if # exists, you can push in a array.
Sample
function getQStoObject(queryString) {
var o = {};
queryString.substring(1).split("&").map(function(str) {
var _tmp = str.split("=");
if (_tmp[1]) {
o[_tmp[0]] = _tmp[1];
}
});
return o
}
var url = "http://rohitazad.com/wealth/tax/how-to-file-your-income-tax-return/newslist/34343443.cms?intenttarget=no&utm_source=newsletter&utm_medium=email&utm_campaign=ETwealth&type=wealth#sid53239948&ncode=23432kjk#%kjimwer";
// window.location.search would look like this
var search = "?intenttarget=no&utm_source=newsletter&utm_medium=email&utm_campaign=ETwealth&type=wealth#sid53239948&ncode=23432kjk#%kjimwer";
var result = getQStoObject(search);
console.log(result)
var hashValues = [];
for(var k in result){
if(result[k].indexOf("#")>-1){
hashValues.push(result[k].split('#')[1]);
}
}
console.log(hashValues)
`
This solution will return you both values following #.
var url = 'http://rohitazad.com/wealth/tax/how-to-file-your-income-tax-return/newslist/34343443.cms?intenttarget=no&utm_source=newsletter&utm_medium=email&utm_campaign=ETwealth&type=wealth#sid53239948&ncode=23432kjk#%kjimwer';
var obj = url.split('?')[1].split('&');
for(var i = 0; i < obj.length; i++) {
var sol = obj[i].split('#');
if(sol[1]) {console.log(sol[1]);}
}

How to obtain the query string from the current URL with JavaScript?

I have URL like this:
http://localhost/PMApp/temp.htm?ProjectID=462
What I need to do is to get the details after the ? sign (query string) - that is ProjectID=462. How can I get that using JavaScript?
What I've done so far is this:
var url = window.location.toString();
url.match(?);
I don't know what to do next.
Have a look at the MDN article about window.location.
The QueryString is available in window.location.search.
If you want a more convenient interface to work with, you can use the searchParams property of the URL interface, which returns a URLSearchParams object. The returned object has a number of convenient methods, including a get-method. So the equivalent of the above example would be:
let params = (new URL(document.location)).searchParams;
let name = params.get("name");
The URLSearchParams interface can also be used to parse strings in a querystring format, and turn them into a handy URLSearchParams object.
let paramsString = "name=foo&age=1337"
let searchParams = new URLSearchParams(paramsString);
searchParams.has("name") === true; // true
searchParams.get("age") === "1337"; // true
The URLSearchParams interface is now widely adopted in browsers (95%+ according to Can I Use), but if you do need to support legacy browsers as well, you can use a polyfill.
Use window.location.search to get everything after ? including ?
Example:
var url = window.location.search;
url = url.replace("?", ''); // remove the ?
alert(url); //alerts ProjectID=462 is your case
decodeURI(window.location.search)
.replace('?', '')
.split('&')
.map(param => param.split('='))
.reduce((values, [ key, value ]) => {
values[ key ] = value
return values
}, {})
If you happened to use Typescript and have dom in your the lib of tsconfig.json, you can do:
const url: URL = new URL(window.location.href);
const params: URLSearchParams = url.searchParams;
// get target key/value from URLSearchParams object
const yourParamValue: string = params.get('yourParamKey');
// To append, you can also leverage api to avoid the `?` check
params.append('newKey', 'newValue');
You can use this for direct find value via params name.
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
This will add a global function to access to the queryString variables as a map.
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query( [queryString] )' which returns an object
// of querystring keys and their values. An optional string parameter can be used as
// an alternative to 'window.location.search'.
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query.makeString( object, [addQuestionMark] )'
// which returns a queryString from an object. An optional boolean parameter can be
// used to toggle a leading question mark.
// -------------------------------------------------------------------------------------
if (!window.location.query) {
window.location.query = function (source) {
var map = {};
source = source || this.search;
if ("" != source) {
var groups = source, i;
if (groups.indexOf("?") == 0) {
groups = groups.substr(1);
}
groups = groups.split("&");
for (i in groups) {
source = groups[i].split("=",
// For: xxx=, Prevents: [xxx, ""], Forces: [xxx]
(groups[i].slice(-1) !== "=") + 1
);
// Key
i = decodeURIComponent(source[0]);
// Value
source = source[1];
source = typeof source === "undefined"
? source
: decodeURIComponent(source);
// Save Duplicate Key
if (i in map) {
if (Object.prototype.toString.call(map[i]) !== "[object Array]") {
map[i] = [map[i]];
}
map[i].push(source);
}
// Save New Key
else {
map[i] = source;
}
}
}
return map;
}
window.location.query.makeString = function (source, addQuestionMark) {
var str = "", i, ii, key;
if (typeof source == "boolean") {
addQuestionMark = source;
source = undefined;
}
if (source == undefined) {
str = window.location.search;
}
else {
for (i in source) {
key = "&" + encodeURIComponent(i);
if (Object.prototype.toString.call(source[i]) !== "[object Array]") {
str += key + addUndefindedValue(source[i]);
}
else {
for (ii = 0; ii < source[i].length; ii++) {
str += key + addUndefindedValue(source[i][ii]);
}
}
}
}
return (addQuestionMark === false ? "" : "?") + str.substr(1);
}
function addUndefindedValue(source) {
return typeof source === "undefined"
? ""
: "=" + encodeURIComponent(source);
}
}
Enjoy.
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.location.search and then extract them with URLSearchParams() class.
const params = new URLSearchParams(window.location.search)
console.log(params.get('product')
// 1
console.log(params.get('category')
// game
Another example using a dynamic url (not from window.location), you can extract the url using URL object.
const url = new URL('https://www.youtube.com/watch?v=6xJ27BtlM0c&ab_channel=FliteTest')
console.log(url.search)
// ?v=6xJ27BtlM0c&ab_channel=FliteTest
This is a simple working snippet:
const urlInput = document.querySelector('input[type=url]')
const keyInput = document.querySelector('input[name=key]')
const button = document.querySelector('button')
const outputDiv = document.querySelector('#output')
button.addEventListener('click', () => {
const url = new URL(urlInput.value)
const params = new URLSearchParams(url.search)
output.innerHTML = params.get(keyInput.value)
})
div {
margin-bottom: 1rem;
}
<div>
<label>URL</label> <br>
<input type="url" value="https://www.youtube.com/watch?v=6xJ27BtlM0c&ab_channel=FliteTest">
</div>
<div>
<label>Params key</label> <br>
<input type="text" name="key" value="v">
</div>
<div>
<button>Get Value</button>
</div>
<div id="output"></div>
You can use this function, for split string from ?id=
function myfunction(myvar){
var urls = myvar;
var myurls = urls.split("?id=");
var mylasturls = myurls[1];
var mynexturls = mylasturls.split("&");
var url = mynexturls[0];
alert(url)
}
myfunction(window.top.location.href);
myfunction("http://www.myname.com/index.html?id=dance&emp;cid=in_social_facebook-hhp-food-moonlight-influencer_s7_20160623");
here is the fiddle
window.location.href.slice(window.location.href.indexOf('?') + 1);
You can use the search property of the window.location object to obtain the query part of the URL. Note that it includes the question mark (?) at the beginning, just in case that affects how you intend to parse it.
You should take a look at the URL API that has helper methods to achieve this in it as the URLSearchParams: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
This is not currently supported by all modern browsers, so don't forget to polyfill it (Polyfill available using https://qa.polyfill.io/).
var queryObj = {};
if(url.split("?").length>0){
var queryString = url.split("?")[1];
}
now you have the query part in queryString
First replace will remove all the white spaces, second will replace all the '&' part with "," and finally the third replace will put ":" in place of '=' signs.
queryObj = JSON.parse('{"' + queryString.replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')
So let say you had a query like abc=123&efg=456. Now before parsing, your query is being converted into something like {"abc":"123","efg":"456"}. Now when you will parse this, it will give you your query in json object.
8 years later, for a one-liner
const search = Object.fromEntries(new URLSearchParams(location.search));
Down-side, it does NOT work with IE11
To explain
The URLSearchParams interface defines utility methods to work with the query string of a URL. (From , https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
The Object.fromEntries() method transforms a list of key-value pairs into an object. (From, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries)
// For https://caniuse.com/?search=fromEntries
> Object.fromEntries(new URLSearchParams(location.search))
> {search: "fromEntries"}
Convert that into array then split with '?'
var url= 'http://localhost/PMApp/temp.htm?ProjectID=462';
url.split('?')[1]; //ProjectID=462
q={};location.search.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v);q;
Try this one
/**
* Get the value of a querystring
* #param {String} field The field to get the value of
* #param {String} url The URL to get the value from (optional)
* #return {String} The field value
*/
var getQueryString = function ( field, url ) {
var href = url ? url : window.location.href;
var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
var string = reg.exec(href);
return string ? string[1] : null;
};
Let’s say your URL is http://example.com&this=chicken&that=sandwich. You want to get the value of this, that, and another.
var thisOne = getQueryString('this'); // returns 'chicken'
var thatOne = getQueryString('that'); // returns 'sandwich'
var anotherOne = getQueryString('another'); // returns null
If you want to use a URL other than the one in the window, you can pass one in as a second argument.
var yetAnotherOne = getQueryString('example', 'http://another-example.com&example=something'); // returns 'something'
Reference
I think it is way more safer to rely on the browser than any ingenious regex:
const parseUrl = function(url) {
const a = document.createElement('a')
a.href = url
return {
protocol: a.protocol ? a.protocol : null,
hostname: a.hostname ? a.hostname : null,
port: a.port ? a.port : null,
path: a.pathname ? a.pathname : null,
query: a.search ? a.search : null,
hash: a.hash ? a.hash : null,
host: a.host ? a.host : null
}
}
console.log( parseUrl(window.location.href) ) //stacksnippet
//to obtain a query
console.log( parseUrl( 'https://example.com?qwery=this').query )
This will return query parameters as an associative array
var queryParams =[];
var query= document.location.search.replace("?",'').split("&");
for(var i =0; i< query.length; i++)
{
if(query[i]){
var temp = query[i].split("=");
queryParams[temp[0]] = temp[1]
}
}
For React Native, React, and For Node project, below one is working
yarn add query-string
import queryString from 'query-string';
const parsed = queryString.parseUrl("https://pokeapi.co/api/v2/pokemon?offset=10&limit=10");
console.log(parsed.offset) will display 10

Get string from url using jQuery?

Say I have http://www.mysite.com/index.php?=332
Is it possible to retrieve the string after ?= using jQuery? I've been looking around Google only to find a lot of Ajax and URL vars information which doesn't seem to give me any idea.
if (url.indexOf("?=") > 0) {
alert('do this');
}
window.location is your friend
Specifically window.location.search
First your query string is not correct, then you can simply take the substring between the indexOf '?=' + 1 and the length of the string. Please see : http://www.w3schools.com/jsref/jsref_substring.asp
When it is easy to do without JQuery, do it with js only.
here is a code snippet (not by me , don't remember the source) for returning a value from a query string by providing a name
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results)
{ return 0; }
return results[1] || 0;
}
var myArgs = window.location.search.slice(1)
var args = myArgs.split("&") // splits on the & if that's what you need
var params = {}
var temp = []
for (var i = 0; i < args.length; i++) {
temp = args[i].split("=")
params[temp[0]] = temp[1]
}
// var url = "http://abc.com?a=b&c=d"
// params now might look like this:
// {
// a: "a",
// c: "d"
// }
What are you trying to do? You very well may be doing it wrong if you're reading the URL.

Categories

Resources