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)

Capitalize string in PHP

In this blog post, you will learn how you can capitalize a string in PHP. We will not use any external library for this purpose. This code can be used in any PHP framework (Laravel, Yii) because I have not used any dependency for it. We will also teach you, how you can update the array element inside foreach loop in PHP.

First, we will explode the string by space.

<?php

// input string
$str = "adnan afzal";

// split words by space
$parts = explode(" ", $str); // ["adnan", "afzal"]
  • explode(delimiter, string): This is a PHP built-in function used to split the string into an array using a delimiter. Here, we are splitting the string using space. So it will return an array of all words in a string.

Then we will loop through all words one-by-one:

// loop through each word
foreach ($parts as $key => $value)
{
    // [section-1]
}

Inside the loop, we will update the word by uppercasing the first letter of each word. Write the following code in [section-1]:

// make first letter uppercase
// and update the word
$parts[$key] = ucfirst($value); // converts ["adnan"] to ["Adnan"]
  • ucfirst(string): This is another PHP built-in function and it is used to uppercase the first letter of the string. So “adnan” will became “Adnan”.

We are converting all the words first letter to uppercase and update the word itself. You can update the array value inside foreach loop using the $key variable.

After the loop, we will join all array parts by space.

// join all words by space
$str = implode(" ", $parts); // converts ["Adnan", "Afzal"] to "Adnan Afzal"

// output string
echo $str;
  • implode(glue, pieces): This function will join the array into a string using a glue. In this case, we are joining the array using space.

Complete code

Following is the complete code to capitalize the string in PHP:

<?php

// input string
$str = "adnan afzal";

// split words by space
$parts = explode(" ", $str); // ["adnan", "afzal"]

// loop through each word
foreach ($parts as $key => $value)
{
    // make first letter uppercase
    // and update the word
    $parts[$key] = ucfirst($value);
}

// join all words by space
$str = implode(" ", $parts);

// output string
echo $str;

Bonus

There might be some cases where you have a value in database like “processing_order” and you want it to display like “Processing Order”. In this case, you just have to add 1 line before using explode() function.

$str = "processing_order";
$str = str_replace("_", " ", $str); // processing order

Then you can apply the above code to capitalize the string. If you want to learn how to capitalize string in Javascript, follow this.

Split camel case using regex in Javascript

Hello. In this post, we will show you, how you can split a camel case word and capitalize it using regex (regular expression) in Javascript.

InputOutput
adnanTechComAdnan Tech Com

Following code will split the camel case into multiple words and then capitalize it:

// splitting camel case to multiple words
const str = "adnanTechCom".replace(/([a-z])([A-Z])/g, "$1 $2")

// capitalizing the string
const capitalize = str.charAt(0).toUpperCase() + str.slice(1)
console.log(capitalize)

capitalize variable will now have value:

Adnan Tech Com

This regular expression will search for all words that ends with small letter and begin with capital alphabet. Then give a space between each of such word.

The above replace call replaces the match of the regex (which happens to match everything) with the first capture group ($1) followed by a space, followed by the second capture group ($2).

For capitalization, you can also use a CSS property as well:

text-transform: capitalize;