Last active
May 3, 2018 07:55
-
-
Save mrroot5/2bbd3fe2eb9ce8e03c64 to your computer and use it in GitHub Desktop.
Capitalize todas las palabras o una sola. From http://codereview.stackexchange.com/questions/77614/capitalize-the-first-character-of-all-words-even-when-following-a
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
| // Opcion 1: Modificando el objeto String | |
| String.prototype.capitalize = function(){ | |
| return this.toLowerCase().replace( /\b\w/g, function (m) { | |
| return m.toUpperCase(); | |
| }); | |
| }; | |
| String.prototype.capitalizeFirstWord = function(){ | |
| return text.charAt(0).toUpperCase() + text.slice(1); | |
| }; | |
| // Opcion 2: definiendo una propiedad del objeto String | |
| Object.defineProperty(String.prototype, 'capitalize', { | |
| value() { | |
| return this.toLowerCase().replace( /\b\w/g, function (m) { | |
| return m.toUpperCase(); | |
| }); | |
| } | |
| }); | |
| Object.defineProperty(String.prototype, 'capitalizeFirstWord', { | |
| value() { | |
| return text.charAt(0).toUpperCase() + text.slice(1); | |
| } | |
| }); | |
| // Opcion 3: Empleando una funcion independiente | |
| function capitalize(capitalize) { | |
| return capitalize.toLowerCase().replace(/\b\w/g, function(m) { | |
| return m.toUpperCase(); | |
| }); | |
| } | |
| function capitalizeFirstWord(text) { | |
| return text.charAt(0).toUpperCase() + text.slice(1); | |
| } | |
| // Uso | |
| var cadena = "foo"; | |
| window.console.log(cadena.capitalize()); | |
| window.console.log(capitalize(cadena)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment