Skip to content

How to Convert String to Title Case in Javascript

If you need to convert a String to Title Case in Javascript, then you can do one of the following:

Option 1 – Using a for loop

function titleCase(str) { str = str.toLowerCase().split(' '); for (var i = ; i < str.length; i++) str[i] = str[i].charAt().toUpperCase() + str[i].slice(1); return str.join(' '); } console.log(titleCase("this is an example of some text!"));
Code language: JavaScript (javascript)

Output: This Is An Example Of Some Text!

Option 2 – Using map()

function titleCase(str) { return str.toLowerCase().split(' ').map(function(word) { return (word.charAt().toUpperCase() + word.slice(1)); }).join(' '); } console.log(titleCase("this is an example of some text!"));
Code language: JavaScript (javascript)

Output: This Is An Example Of Some Text!

Option 3 – Using replace()

function titleCase(str) { return str.toLowerCase().split(' ').map(function(word) { return word.replace(word[], word[].toUpperCase()); }).join(' '); } console.log(titleCase("this is an example of some text!"));
Code language: JavaScript (javascript)

Output: This Is An Example Of Some Text!

See also  How to Style an Element using Javascript
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x