Skip to content

Instantly share code, notes, and snippets.

@jherax
Last active May 30, 2020 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jherax/e6ecb05aa35eb0219525 to your computer and use it in GitHub Desktop.
Save jherax/e6ecb05aa35eb0219525 to your computer and use it in GitHub Desktop.
Gets values from the url search
/* eslint-disable no-underscore-dangle */
/**
* Supported types
*/
const TYPES = {
_true: /^true$/i,
_false: /^false$/i,
_null: /^null$/i,
_number: /^[0-9]+$/,
_object: /^[{[].*[\]}]$/,
};
function tryParse(value) {
try {
return JSON.parse(value);
} catch {
return value;
}
}
/**
* Parses the input value to the correct data type.
*
* @param {any} value - value to test its type
* @returns {any}
*/
function parseType(value) {
if (TYPES._number.test(value)) return +value;
if (TYPES._true.test(value)) return true;
if (TYPES._false.test(value)) return false;
if (TYPES._object.test(value)) return tryParse(value);
if (TYPES._null.test(value)) return null;
return value;
}
/**
* Decodes a string with `decodeURIComponent`
*
* @param {string} value - string to url-decode
* @returns {string}
*/
function getValue(value) {
return decodeURIComponent(value.replace(/\++/g, ' ')).trim();
}
/**
* Try to parse the string to a primitive value.
*
* @param {string} value - string to parse
* @param {function} parser - (optional) callback that receives a string and returns a transformed string
* @returns {any}
*/
export default function parseValue(value, parser = getValue) {
let parsed = parseType(parser(value));
// prevents a string starting with "0" from be converted to a number
return typeof parsed === 'number' && String(parsed).length !== value.length ? value : parsed;
}
import parseValue from './_parseValue';
/**
* Gets a parameter's value from the URL search.
* @see https://gist.github.com/jherax/e6ecb05aa35eb0219525
*
* @param {string[]} args - arguments list. It can be one of the following:
* @param {string} url - (optional) URL from where extract the search parameters
* @param {string} key - name of the parameter in the url-search
* @returns {any}
*/
export default function getUrlParameter(...args) {
let url, key;
let value = '';
if (args.length > 1) {
[url, key] = args;
} else {
url = window.location.search;
key = args[0];
}
if (!key) return '';
const m = url.match(new RegExp(`(${key})=([^&#]+)`));
if (m) value = parseValue(m[2]);
return value;
}
import parseValue from './_parseValue';
const SEPARATORS = /[?&#]/g;
/**
* Gets values from the URL-search and store them in an object.
* @see https://gist.github.com/jherax/e6ecb05aa35eb0219525
*
* @param {string} url: (optional) URL from where extract the search parameters
* @param {string} key: (optional) specific parameter in the url-search to extract
* @return {object}
*/
export default function urlParamsToObject(url = window.location.search, key) {
const queryObj = {};
let pkey, value;
if (!url) return queryObj;
const params = url.split(SEPARATORS).filter(p => p);
params.forEach((param) => {
[pkey, value] = param.split('=');
if (!value) return; // continue
// key and value were encoded with encodeURIComponent
pkey = decodeURIComponent(pkey).trim();
if (!key || pkey === key) {
value = parseValue(value);
// if parameter was set already, then builds an array of values
// if (pkey in queryObj) value = [].concat(queryObj[pkey], value);
queryObj[pkey] = value;
}
});
return queryObj;
}
var url = 'https://jherax.wordpress.com/?SRC=null&subid=102&pubid=001&utm_content=false&utm_source=google&utm_term=market%20place';
// get the value of 'x2' in the current url
getUrlParameter('x2'); // -> ""
// get the value of 'subid' in the url provided
getUrlParameter(url, 'subid'); // -> 102
// get the value of 'utm_term' in the url provided
getUrlParameter(url, 'utm_term'); // -> "market place"
// get the value of 'q' in the uri provided
getUrlParameter('?q=the+black+mirror', 'q'); // -> "the black mirror"
var url = 'https://jherax.wordpress.com/?SRC=null&subid=900&pubid=001&utm_content=false&utm_term=market%20place';
// get all search-parameters in the current url
var params = urlParamsToObject();
console.log(params);
// get all search-parameters in the url provided
var params = urlParamsToObject(url);
console.log(params);
// {SRC: null, subid: 900, pubid: "001", utm_content: false, utm_term: "market place"}
// get only the 'q' parameter in the uri provided
var utm_term = urlParamsToObject('?q=the+black+mirror', 'q');
console.log(utm_term);
// { q: "the black mirror" }
// get all parameters from the uri provided, including url-encoded-json values
var query = "?id=6716&data=%7B%22category%22%3A%22laptop%22%2C%22brands%22%3A%5B%22DELL%22%2C%22ASUS%22%5D%7D";
var params = urlParamsToObject(query);
console.log(params);
/*
{
id: 6716,
data: {
category: "laptop",
brands: ["DELL", "ASUS"]
}
}
*/
/*
NOTE:
If the url contains an encoded and well formed JSON,
(e.g. from toUrlParams) it can be converted again to an object.
See: https://gist.github.com/jherax/7dd42406ebe2a2dc978c054f4f54c62e
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment