Skip to content

Instantly share code, notes, and snippets.

@blizzrdof77
Last active September 19, 2022 20:02
Show Gist options
  • Save blizzrdof77/b57cd71168d4999da5837a1001337bc7 to your computer and use it in GitHub Desktop.
Save blizzrdof77/b57cd71168d4999da5837a1001337bc7 to your computer and use it in GitHub Desktop.
Javascript String Prototype Helper Methods
/**
* Helper String Methods/Extensions to the JS String Object
*
* @param String search
* @return Bool
*/
String.prototype.contains = function(search) {
return (this.indexOf(search) !== -1);
};
String.prototype.replaceAll = function(find, replacement) {
return this.replace(new RegExp(find, 'g'), replacement);
};
/**
* Case conversion helper methods
*
* @type String
* @return String
*/
String.prototype.toTitleCase = function() {
return this.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
};
String.prototype.camelCaseToDashed = function() {
return this.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
};
String.prototype.toProperCase = function() {
return this.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
};
String.prototype.toCamelCase = function() {
return this.replace(/(?:^\w|\-[A-Z]|\b\w)/g, function(letter, index) {
return index == 0 ? letter.toLowerCase() : letter.toUpperCase();
}).replace(/\s+/g, '').replace('-', '');
};
String.prototype.toDashedCase = function() {
return this.toCamelCase().camelCaseToDashed();
};
@blizzrdof77
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment