This page looks best with JavaScript enabled

Convert String to Title Case in Javascript

 ·   ·  ☕ 1 min read

We have a string.toLowerCase() and string.toUpperCase() in Javascript, but no out of the box function to convert to title case. Fear not if you are in that pickle - it is quite easy.

1
2
3
4
5
6
7
8
9
function ConvertTitleCase(str) {
  const strArr = str.toLowerCase().split(" ");
  for (let i = 0; i < strArr.length; i++) {
    strArr[i] = strArr[i][0].toUpperCase() + strArr[i].slice(1);
  }
  return strArr.join(" ");
}

console.log(ConvertTitleCase("hello world")); // Hello World

ConvertTitleCase takes one argument, which is a string. The string is split into distinct word array (split at ‘space’), and each word is then converted to initial cap.

The below statement converts first char of the word to upper case, and joins the upper case letter with rest of the chars in the word.

1
strArr[i] = strArr[i][0].toUpperCase() + strArr[i].slice(1);

The changed array is joined back to form a string with a space in between words. The string with title case is then returned to the caller.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things