Skip to content

Instantly share code, notes, and snippets.

@fliptopbox
Created November 13, 2013 12:33
Show Gist options
  • Save fliptopbox/7448344 to your computer and use it in GitHub Desktop.
Save fliptopbox/7448344 to your computer and use it in GitHub Desktop.
Some String prototype extensions that are handy
/* Additional Primative Object Extensions */
String.prototype.capitals = function () {
// 'kilRoY waS hErE!' >> 'Kilroy Was Here!'
return (this || '').replace(/([^ ])([^ ]*)/g,
function(a,b,c) { return b.toUpperCase() + c.toLowerCase(); });
};
String.prototype.snake = function () {
// 'kilRoY waS hErE!' >> 'kilRoY_waS_hErE!'
return (this || '').replace(/\s+/g, '_');
};
String.prototype.camel = function () {
// 'kilRoY waS hErE!' >> 'KilroyWasHere!'
return (this || '').replace(/([^ ])([^ ]*)/g,
function(a,b,c) { return b.toUpperCase() + c.toLowerCase(); })
.replace(/\s+/gi, '');
};
String.prototype.querystring = function (isOrdered) {
var tmp;
var stringValue = this || null;
isOrdered = (isOrdered === true);
// strip: hostname and ? (prefix) and # (suffix) and trim white space
stringValue = stringValue.replace(/^(.*)?\?|#.*$|^\s+|\s+$/gi, '');
// integrity check.
if (!stringValue.length) { return {}; }
// what if the querystring is /?aSingleKeyValue
if (stringValue.indexOf('=') < 0) {
tmp = {};
tmp[stringValue] = stringValue;
return tmp;
}
// prepare key/value pairs for JSON.parse()
tmp = stringValue.replace(/\=/gi, ':'); // make '=' into ':'
tmp = tmp.replace(/&/gi, ','); // make '&' into ','
tmp = tmp.replace(/([^:]+):([^,]*)(,)?/gi, '"$1":"$2"$3'); // wrap key and value with "
// order the stringValue alphabetically
tmp = isOrdered ? (tmp.split(',').sort().join(',')) : tmp;
// convert integer numbers and boolean values into their primative type
// ie. "true" -> true or "123" -> 123 or "null" -> null
tmp = tmp.replace(/:"([0-9]+(\.[0-9]+)?|null|true|false)"/gi, ':$1');
//console.log(stringValue, tmp, LBI.common.getStringQueriesX(stringValue));
return JSON.parse(['{', tmp, '}'].join(''));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment