There isn’t a built-in method to capitalize a word, so we have to use others and modify them to suit our required output. There are four methods we will use:
- toUpperCase() – This method capitalizes all the characters of a string and returns it in uppercase. To use this method, you need to call it on a string and store the result in a new variable.
- 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 into all lowercase 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('');
You can also use regular expressions to capitalize the first letter of a string using a regular expression. To use this method, you need to create a regular expression pattern that matches the first letter of a string and call the
replace() method on it.