Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save onedayitwillmake/0a73bde2870593f5e26e47777ac9aced to your computer and use it in GitHub Desktop.
Save onedayitwillmake/0a73bde2870593f5e26e47777ac9aced to your computer and use it in GitHub Desktop.
getParameterByNameUsingDefaultValue.js
/**
* @copyright 2015 Apple Inc. All rights reserved.
* @author supermario@apple.com
*/
'use strict';
var cachedValues = {};
/**
* Returns URL parameter if available, if not returns `defaultValue`
* @param {String} name Name of URL parameter to look for
* @param {*} defaultValue Default value used if `name` is not found
* @param {Boolean=false} preventCaching If true value is never cached, useful for non onetime use parameters
* @return {*}
*/
module.exports = function getParameterByNameUsingDefaultValue(name, defaultValue, preventCaching) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
if(preventCaching || !cachedValues.hasOwnProperty(name)) {
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
var results = regex.exec(location.search);
var value = (results === null) ? defaultValue : decodeURIComponent(results[1].replace(/\+/g, " "));
// naive but good enough string to bool conversion
if(value === "true" || value === "false") value = (value === "true");
// naive but good enough string to number conversion
if( !isNaN( parseFloat(value) ) ) value = parseFloat(value);
cachedValues[name] = value;
}
return cachedValues[name];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment