How to Convert String to Title Case in Javascript

0 min read 134 words

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 = 0; i < str.length; i++)
    str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1); 
  return str.join(' ');
}

console.log(titleCase("this is an example of some text!"));

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(0).toUpperCase() + word.slice(1));
  }).join(' ');
}

console.log(titleCase("this is an example of some text!"));

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[0], word[0].toUpperCase());
  }).join(' ');
}

console.log(titleCase("this is an example of some text!"));

Output: This Is An Example Of Some Text!

Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags