Created
December 8, 2016 20:33
-
-
Save onedayitwillmake/0a73bde2870593f5e26e47777ac9aced to your computer and use it in GitHub Desktop.
getParameterByNameUsingDefaultValue.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @copyright 2015 Apple Inc. All rights reserved. | |
* @author [email protected] | |
*/ | |
'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