Last active
September 19, 2022 20:02
-
-
Save blizzrdof77/b57cd71168d4999da5837a1001337bc7 to your computer and use it in GitHub Desktop.
Javascript String Prototype Helper Methods
This file contains hidden or 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
/** | |
* Helper String Methods/Extensions to the JS String Object | |
* | |
* @param String search | |
* @return Bool | |
*/ | |
/* Easier way to check if a string contains a substring */ | |
String.prototype.contains = String.prototype.contains || function(search) { | |
return (this.indexOf(search) !== -1); | |
}; | |
/* Check if a string contains any substring within an array of passed strings */ | |
String.prototype.containsAny = String.prototype.containsAny || function(arr) { | |
for (var i = 0; i < arr.length; i++) { | |
if (this.indexOf(arr[i]) > -1) { | |
return true; | |
} | |
} | |
return false; | |
}; | |
String.prototype.replaceAll = 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 = String.prototype.toTitleCase || function() { | |
return this.replace(/\w\S*/g, function(txt) { | |
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); | |
}); | |
}; | |
String.prototype.camelCaseToDashed = String.prototype.camelCaseToDashed || function() { | |
return this.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); | |
}; | |
String.prototype.toProperCase = String.prototype.toProperCase || function() { | |
return this.replace(/\w\S*/g, function(txt) { | |
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); | |
}); | |
}; | |
String.prototype.toCamelCase = String.prototype.toCamelCase || function() { | |
return this.replaceAll('-', '_').replaceAll('_', ' ').replace(/(?:^\w|\-[A-Z]|\b\w)/g, function(letter, index) { | |
return index == 0 ? letter.toLowerCase() : letter.toUpperCase(); | |
}).replace(/\s+/g, '').replace('-', ''); | |
}; | |
String.prototype.toKebabCase = String.prototype.toKebabCase || function(uppercase = false) { | |
let str = this.toCamelCase().camelCaseToDashed(); | |
return (uppercase ? str.toUpperCase() : str); | |
}; | |
String.prototype.toSnakeCase = String.prototype.toSnakeCase || function(capitalize = false) { | |
let str = this.toKebabCase().replaceAll('-', '_'); | |
return (capitalize ? str.replaceAll('_', ' ').toTitleCase().replaceAll(' ', '_') : str); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://cdn.simpledigital.net/common/js/extensions/String.prototypeHelpers.js