Capitalize string in Javascript

In one of our blog post, we capitalized the string in PHP. In this, we will show you, how you can capitalize the string in Javascript. The code used in this tutorial can be used in any Javascript framework or library like React.js, Vue.js, Angular etc.

The first thing we need to do is to split the string using space.

let str = "adnan afzal"
const parts = str.split(" ") // ["adnan", "afzal"]

split(delimiter): Is a function in Javascript that can be chained on strings. It will split the string into parts using delimiter and return it as an array.

Then we will loop through all parts of that array.

for (let a = 0; a < parts.length; a++) {
    // [section-1]
}

After that, we will first convert the first letter of the word to uppercase. Then we will return the remaining letters in that word and concatenate them.

// uppercase first letter
const firstLetter = parts[a][0].toUpperCase()

// return string except for first character (as it is uppercased)
const remainingStr = parts[a].substr(1)

// concatenate both strings
parts[a] = firstLetter + remainingStr

toUpperCase(): A Javascript function that can be called from string and will return the uppercase version of that string.

substr(start): This function can also be called from strings. It will return the remaining string starting from start parameter.

  • parts[a]: This will get the current word in the iteration. For example “adnan”.
  • parts[a][0]: This will get the first letter of the current word. For example “a”.
  • parts[a][0].toUpperCase(): Converts “a” to “A”.
  • parts[a].substr(1): Returns the string skipping the first character i.e. “dnan”.

Thus concatenating “A” and “dnan”, we get “Adnan”. This will do for each word. The last thing we need to do is to combine all the capitalized words together. Following code goes after the loop.

str = parts.join(" ")
console.log(str) // Adnan Afzal

This will join the array by space and return it as string.

Bonus

If you are calling an API that is returning fields like “processing_order”, then you must first remove the underscore and replace it with space.

let str = "processing_order"
str = str.split("_").join(" ") // "processing order"
  • split(“_”): This will split the string by underscore and return it as an array i.e. [“processing”, “order”].
  • join(” “): This will join the array using space, thus return the complete string as “processing order”.

We are using this method instead of Javascript replace() function in order to replace all the occurrences of “_” with an empty space.

After that you can apply the above method to capitalize the string.

Complete code

Complete code to capitalize the string in Javascript is:

let str = "adnan afzal"
const parts = str.split(" ")
for (let a = 0; a < parts.length; a++) {
    const firstLetter = parts[a][0].toUpperCase()
    const remainingStr = parts[a].substr(1)
    parts[a] = firstLetter + remainingStr
}
str = parts.join(" ")
console.log(str)