How to Convert String to Title Case in JavaScript [3 Ways]

There are no direct ways to convert a string to a title case in JavaScript, but you can use a combination of different methods.

Here are three ways to convert a string to a title case in JavaScript:

  1. Using String.prototype.split(), Array.prototype.map(), and String.prototype.slice()
  2. Using String.prototype.replace() and regex
  3. Using for loop

Method 1: Using String.prototype.split(), Array.prototype.map(), and String.prototype.slice()

In JavaScript, you can convert a string to a title case using the combination of the String.prototype.split(), Array.prototype.map(), and String.prototype.slice() methods.

function toTitleCase(str) {
  return str.split(' ').map(function (word) {
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  }).join(' ');
}

console.log(toTitleCase("hello world")); 

Output

Hello World

Method 2: Using String.prototype.replace() and regex

You can convert a string to a title case using the String.prototype.replace() method with a regular expression(regex).

function toTitleCase(str) {
  return str.replace(/\w\S*/g, function (word) {
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  });
}

console.log(toTitleCase("hello world"));

Output

Hello World

Method 3: Using for loop

Here’s how you can convert a string to a title case using a for loop:

function toTitleCase(str) {
  let words = str.split(' ');
  for (var i = 0; i < words.length; i++) {
    words[i] = words[i].charAt(0).toUpperCase()
     + words[i].slice(1).toLowerCase();
  }
  return words.join(' ');
}

console.log(toTitleCase("hello world"));

Output

Hello World

That’s it!

Related posts

How to Convert an Array to Lowercase

How to Convert an Array to Uppercase