javascript

How to Capitalize Text with JavaScript


In this article, you will learn to Capitalize Text with JavaScript. JavaScript has built-in methods like .toLowerCase() – to convert text to lower case – and .toUpperCase() – to convert text to upper case. However, there’s no built-in method to convert text to title case i.e. “How Are You”. However, we can combine .toUpperCase() with another method .charAt() to achieve this result.

<p id="name">john doe</p>
<button onclick="capitalize('john doe')">Capitalize Name</button>

We start off with some markup. A paragraph with the text we want to capitalize and a button to trigger the method to capitalize the text.

function capitalize (value) {
  var textArray = value.split(' ')
  var capitalizedText = ''
  for (var i = 0; i < textArray.length; i++) {
    capitalizedText += textArray[i].charAt(0).toUpperCase() + textArray[i].slice(1) + ' '
  }
  document.getElementById('name').innerText = capitalizedText.trim()
}

The method gets the text that was passed and splits it into an array, using an empty string (‘ ‘) as the delimiter. It loops through the array. For each string in the array, we get the first letter of the string (charAt(0)) and convert it to upper case. Then gets the remaining parts of the string using slice(1). It then concatenates both parts into one string and so on. Finally, it replaces the paragraph text with the new title-cased text.

You may want to exempt conjunctions/articles like “the”, “of”, “a” or any other words from being capitalized. In that case, modify the code like so:

function capitalize (value) {
  var textArray = value.split(' ')
  var capitalizedText = ''
  var conjunctions = ['the', 'of', 'a']
  for (var i = 0; i < textArray.length; i++) {
    if (conjunctions.includes(textArray[i]) {
      continue
    }
    capitalizedText += textArray[i].charAt(0).toUpperCase() + textArray[i].slice(1) + ' '
  }
  document.getElementById('name').innerText = capitalizedText.trim()
}

You simply add all the exemptions to an array. In the loop, you check if the current string is part of the excluded list (.includes()). If it is, then skip the rest of that loop iteration (continue).

Use Cases

  • Blog titles
  • News article titles

Share on social media

//