How to Convert String to Title Case with JavaScript

In JavaScript, there is no direct way of converting a string to title case. However, the combination of multiple methods can solve the problem. Let’s convert capitalize first letter of each word together. There are several ways of converting.

map()

One of the methods is the map() method. Before applying this method, firstly, you should lowercase and split the string:

Javascript map method
function toTitleCase(str) { return str.toLowerCase().split(' ').map(function (word) { return (word.charAt(0).toUpperCase() + word.slice(1)); }).join(' '); } console.log(toTitleCase("welcome to w3docs"));

replace()

The second method converts a string by matching the first letter of each word and replacing it with its upper case equivalent.You can also use a regex as a pattern:

Javascript replace method converts a string by matching the first letter
function toTitleCase(str) { return str.replace( /\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); } ); } console.log(toTitleCase("WELCOME TO W3DOCS"));

for loop

The third method that is used to make the string title case is the for loop:

Javascript make the string title case is the for loop
function toTitleCase(str) { str = str.toLowerCase().split(' '); for (var i = 0; i < str.length; i++) { str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1); } return str.join(' '); } console.log(toTitleCase("WELCOME TO W3DOCS"));

The map() Method

The map() method generates a new array with the output of calling a provided function on every element in the specified array. The method calls a provided callback function only once for each element in an array, and generates a new array from the outputs. Callback is executed only for indexes of the array which have assigned values including undefined.

The replace() Method

The replace() method executes a search for a match in a string, and replaces the matched substring with a replacement one. The pattern can be either a string or a regular expression. The replacement can be either a string or a function that is called for each match. If the pattern is a string, only the first occurrence will be replaced, and the initial string will be left unchanged.

The for loop

The for loop is used for executing a block of code for a certain number of times. The for loop consists of three optional expressions that are placed in parentheses and separated by semicolons followed by a statement to be invoked in the loop.