Last active
March 3, 2017 15:36
-
-
Save lcfd/a3e41e950cdf169fb18baa12d0fe9116 to your computer and use it in GitHub Desktop.
A collection of useful prototypes that I use.
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
/** | |
* First letter of a string converted into uppercase | |
*/ | |
String.prototype.capitalizeFirstLetter = function () { | |
return this | |
.charAt(0) | |
.toUpperCase() + this.slice(1); | |
} | |
/** | |
* ES6 template strings in ES5 | |
*/ | |
String.prototype.eval = function (data) { | |
return this.replace(/\${(.*?)}/g, function (_, code) { | |
var scoped = code.replace(/(["'\.\w\$]+)/g, function (match) { | |
return /["']/.test(match[0]) | |
? match | |
: 'scope.' + match | |
}); | |
try { | |
return new Function('scope', 'return ' + scoped)(data) | |
} catch (e) { | |
return '' | |
} | |
}) | |
} | |
/** | |
* Add a number to all the elements | |
*/ | |
Array.prototype.addToAll = function (adder) { | |
return this.map(function (x) { | |
return x + adder; | |
}); | |
} | |
/** | |
* Slugify the string | |
*/ | |
String.prototype.slugify = function () { | |
return this | |
.toString() | |
.toLowerCase() | |
.replace(/\s+/g, '-') | |
.replace(/[^\w\-]+/g, '') // Remove all non-word chars | |
.replace(/\-\-+/g, '-') // Replace multiple - with single - | |
.replace(/^-+/, '') // Trim - from start of text | |
.replace(/-+$/, ''); // Trim - from end of text | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment