Skip to content

Instantly share code, notes, and snippets.

@osiyuk
Created November 8, 2016 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save osiyuk/a4b8fa0fc72c283adfb99920acb6f646 to your computer and use it in GitHub Desktop.
Save osiyuk/a4b8fa0fc72c283adfb99920acb6f646 to your computer and use it in GitHub Desktop.
// https://gist.github.com/osiyuk/d18ec38ceae0e12f7a6ed7be9077b6f7
// prototype forwarding
// ...or monkey patching
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
}
@Aathi
Copy link

Aathi commented Apr 18, 2020

this is a simple method to convert and able to pass value to get desire output.

String.prototype.toChangeCase = function (type) {
    switch (type) {
        case 'upper-first':
            return this.charAt(0).toUpperCase() + this.substr(1).toLowerCase();
        case 'upper-each':
            return this.split(' ').map(word => {
                return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase();
            }).join(' ');
        default:
            throw Error(`In order to get the output pass a value 'upper-first', 'upper-each'`);
    }
}

Outputs

"capitalize first Letter of Each word in a Sstring".toChangeCase('upper-first')
"Capitalize first letter of each word in a sstring"


"capitalize first Letter of Each word in a Sstring".toChangeCase('upper-each')
"Capitalize First Letter Of Each Word In A Sstring"

"Capitalize First Letter Of Each Word In A String".toChangeCase()
VM380:12 Uncaught Error: In order to get the output pass a value 'upper-first', 'upper-each'
    at String.toChangeCase (<anonymous>:12:19)
    at <anonymous>:16:52

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