There isn’t a built-in method to capitalize a word, so we have to use others and modify to suit our required output. There are four methods we will use:
- toUpperCase() – The toUpperCase() method makes the string you give it uppercase.
- slice() – The slice()method extracts part of a string, returning it as another string without touching the original.
- charAt() – The String object’s charAt() method returns a new string consisting of the single UTF-16 code unit (a number between 0 and 65535) located at the specified offset into the string.
- toLowerCase() – The toLowerCase() method converts the string value passed in to all lower case letters.
- subsrtring() – The substring() method returns the part of the string between the start and end indexes, or the whole of it.
Here are some methods which can capitalize a word:
let output = ''; //no need to redefined for all exmaples let source = 'WoRD'; output = source.charAt(0).toUpperCase() + source.toLowerCase().slice(1); output = source.toUpperCase() + source.slice(1).toLowerCase(); output = source.toUpperCase() + source.substring(1).toLowerCase(); output = source.split('').map((character, index) => index ? character.toLowerCase() : character.toUpperCase()).join('');