Last active
December 21, 2015 16:02
-
-
Save placenamehere/f5ade9012b0ad1229215 to your computer and use it in GitHub Desktop.
some universal helper functions i frequently grab
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
var Util = window.Util || {}; | |
/** | |
* Generic utility functions | |
*/ | |
Util = (function() { | |
'use strict'; | |
return { | |
// safari toLocaleString() just returns same as toString(), rather than inserting commas for en-US | |
// so add commas and other formatting specific to US | |
toUSLocaleNumber: function(x) { | |
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); | |
}, | |
// returns true if current document is not the top most document | |
isFramed: function() { | |
return (window.self !== window.top); | |
}, | |
// returns all URL params as key-value pairs | |
// via https://css-tricks.com/snippets/jquery/get-query-params-object/ | |
getQueryParameters: function(str) { | |
return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0]; | |
}, | |
// performs replacement on query params in a given elements href attr | |
setQueryParamVal: function(param, val, uri) { | |
var re = new RegExp('([?|&])' + param + '=.*?(&|$)', 'i'), | |
sep = uri.indexOf('?') !== -1 ? '&' : '?'; | |
uri = uri ? uri : document.location.href; | |
if (uri.match(re)) { | |
uri = uri.replace(re, '$1' + param + '=' + val + '$2'); | |
} else { // just add it to the end | |
uri = uri + sep + param + '=' + val; | |
} | |
return uri; | |
}, | |
// does a simple string replace for %S | |
// but do it safely because we might have to pass null as the pattern | |
stringReplace: function(text,template) { | |
if (template == null) { | |
return text; | |
} else { | |
return template.replace('%S',text); | |
} | |
}, | |
} | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment