Capitalize First Letter of Each Word in a String Javascript

Capitalize First Letter of Each Word in a string in JavaScript

In this article, we’ll look at how to capitalize the first letter of each word in a string in Javascript according to its characteristics. We’ll investigate different ways of approaching the task and how we can divide it to find the solution that best fits our needs.

Related articles:

  1. Capitalize First Letter in JavaScript | 4 Ways to Make the First Letter of a String Uppercase

Consider the peculiarities of the input (string)

If we better understand what type of input we’ll receive, the chances of solving the problem increase twice. We need to ask ourselves questions like:

  1. Does the string contain different sorts of whitespace as tabs, new lines, and spaces?
  2. Do we need to retain the original variant of the string after capitalizing it? – for example, if we have a multiline string whether it is required to save the new lines in the capitalized one.
  3. Does the string contain numeric characters?

Capitalize the First Letter of Each Word in a String using String.split()

The words in the string are separated by spaces only

Hence, the string doesn’t contain tabs or new lines:

const str = 'I know how to solve problems!';

We have to divide the string into separate words. One way to accomplish this is to use the String.split() method that takes a pattern as a parameter indicating how the string will be divided, then returns an array of substrings. We’ll pass a space as an argument, and we can get each word from the string as an element of the list.

// We divided the string using the split(' ') method
// It separated the string by ' ' spaces.
//And returned an array of words.
console.log(str.split(' ')); // --> ['I', 'know', 'how', 'to', 'solve', 'problems!']

Now each array element represents a separate word. Loop through it, extract the first letter of each word using charAt(0) (the first character of the string is at index 0), then use toUpperCase() to make it capital. Take out the remaining part of the word using slice(1). It will create a new substring derived from index 1 to the end index of the original string. For example, look at the following image:

const myString = 'masculine';

//takes the first character from the string. The counting starts from 0.
const firstCharacter = myString.charAt(0);

console.log(firstCharacter); // --> m

//Makes the character capital letter
console.log(firstCharacter.toUpperCase()); // --> M

//Combine the first character with the remaining part
// M + asculine => Masculine
const word = firstCharacter.toUpperCase() + myString.slice(1); 
console.log(word);

 Output:

m
M
Masculine

We can call the above code for each element of the array, then join each word into a new string using the join(‘ ‘) method (the argument is a space; hence, it will combine each item with ‘ ‘ in between).

The final solution for a string with spaces looks like this:

const str = 'I know how to solve problems!';
const arrOfWords = str.split(' ')
.map(singleWord => singleWord.charAt(0).toUpperCase() + singleWord.slice(1));
console.log(arrOfWords.join(' '));

Output:

I Know How To Solve Problems!

Now we found a solution for a simple string, but what if it contains new lines, tabs, and spaces…

The string is multiline that contains different types of whitespace

Let’s examine the following string:

const str = `you know 
         how       to
  solve 
     problems!`;

As you can see, it contains tabs, line breaks, and spaces. In this case, we cannot use a space (‘ ‘) as a divider in the split() method. Instead, we have to use a regex that matches any whitespace character. We’ll use the following tokens:

  • \s – Matches any whitespace character (tabs, line breaks, and spaces)
  • + – Match one or more of the preceding token
  • g – allows iterative search
regex that matches any whitespace character -tabs, spaces, and new lines

The blue lines indicate what the regex cover from our text.

Let’s use it in the split(/[\s]+/g) method to divide each word.

const str = `you know 
         how       to
  solve 
     problems!`;
const regex = /[\s]+/g;
console.log(str.split(regex));

Output:

(6) ['you', 'know', 'how', 'to', 'solve', 'problems!']

We reached the point where we can apply the same technique as above – the output is an array of words.

const str = `you know 
         how       to
  solve 
     problems!`;
const regex = /[\s]+/g;
const arrOfWords = str.split(regex)
.map(word => word.charAt(0).toUpperCase() + word.slice(1));
console.log(arrOfWords.join(' '));

Output:

You Know How To Solve Problems!

The above code capitalizes the first letters but doesn’t retain the original form of the string. It replaces all tabs and line breaks with spaces.

Capitalize the First Letter of Each Word in a String using String.match()

The String.match() method retrieves the result of matching a string against a regular expression:

const str = 'You Are SuperHuman';

//what characters to cover 
// the regex will cover character in range A-Z (capital letters)
const regex = /[A-Z]/g;
// the regex is passed as an argument

// it returns all matches
const found = str.match(regex);
console.log(found);

Output:

 ['Y', 'A', 'S', 'H']

Get each word from a string using match()

There’s no matter whether the string contains different whitespace characters if we use the match method to extract each word. Imagine we have these strings:

const multilineStr = `you know 
         how       to
  solve 
     probles`;

const singleLineStr = 'you know how to solve programming problems';
  • multilineStr contains tabs, spaces, and line breaks.
  • singleLineStr contains only spaces.

To get each word we need a regex that covers alphabetical case-insensitive characters only. In the previous example, we ‘catch’ the capital letters using /[A-Z]/g , so we have to expand the range in between [a - z] for all small letters. The final expression looks like this:

/ [A-Za-z]+/g- The expression matches all alphabetical characters

regex alphabetical characters match with aplus sign
  • A-Z – It matches characters from A – Z
  • a-z – It matches characters from a – z
  • + – Matches one or more of the preceding tokens. For example, it indicates that the letters will be enveloped into a single word. If we don’t use the sign, each letter will be considered as a single match.

A regular expression without a plus sign:

A regular expression - matches all alphabetical characters without +

As you can see, the blue background of each letter indicates that each character is a separate match.

Now we found the correct regular expression and we’ll pass it to the match method.

const multilineStr = `you know 
         how       to
  solve 
     problems`;

const singleLineStr = 'you know how to solve programming problems';

const regex =  /[A-Za-z]+/g;
const arrOfMultilineStr = multilineStr.match(regex);
const arrOfSingleLineStr = singleLineStr.match(regex);

console.log('Array of all words from  multilineStr: ' + arrOfMultilineStr);
console.log('Array of all words from  singleLineStr: ' + arrOfSingleLineStr);

Output:

Array of all words from  multilineStr: you,know,how,to,solve,problems
Array of all words from  singleLineStr: you,know,how,to,solve,programming,problems

It returned two arrays with items representing different words.

Capitalize each word in the returned arrays

We already know how to make each word from an array uppercase.

const upperCasedArr = arrOfMultilineStr
.map(word => word.charAt(0).toUpperCase() + word.slice(1));
console.log(upperCasedArr.join(' '));

Output:

You Know How To Solve Probles

If we want to capitalize the second string:

const upperCasedArray = arrOfSingleLineStr
.map(word => word.charAt(0).toUpperCase() + word.slice(1));
console.log(upperCasedArray.join(' '));

Output:

You Know How To Solve Programming Problems

Note: If you have a multiline string and you want to use the match method in this particular way, keep in mind that you’ll lose all tabs, and line breaks in the uppercased string because at the end you join each word by space only.

Get each word of the string if contains alphanumeric values and punctuation marks using the match method

Consider you have a string like this:

const yourString = `you are superhuman! you are number 1 
you have super powers, abilities...`;

We have to change the regular expression:

const regex = /[\w,!.';:?]+/g;

We can solve the problem by choosing the same approach as the above example but we have to alter the regex for our needs.

  • \w – matches any word character (alphabetical or numeric)
  • ,!.’;:? – matches these punctuational marks

Use the above regular expression and pass it to the match method.

const regex =  /[\w,!.';:?]+/g;
const arr = yourString.match(regex);

const upperCasedArr = arr
.map(word => word.charAt(0).toUpperCase() + word.slice(1));
console.log(upperCasedArr.join(' '));

Output:

You Are Superhuman! You Are Number 1 You Have Super Powers, Abilities...

Capitalize each word from the string using the replace() method

If you have a string with tabs and line breaks and want to keep the original form of it, use replace().

The replace(pattern, replacement) method returns a new string with one, some, or all matches of a pattern replaced by a replacement. . The pattern can be a string or a regular expression. It can take function as a replacement (source: MDN-replace)

So we have to find a way to extract the first letter with the preceding type of whitespace for each word in the string. For our regex, we can use tokens like this /[\s]+[\w]|^[\w]/g :

  • \s – matches whitespaces like tabs, spaces, and line breaks
  • | – logical OR
  • [\w]- matches all alphanumeric characters
  • ^ – matches the beginning of the string
  • [\s]+[\w] – matches the first letter of each word with preceding whitespaces
  • ^[\w] – matches the first letter of the beginning of the string, we’ll use it because the first character of the string doesn’t have a whitespace before it.
Regular expression and replace to uppercase first letter of each word in string
function solve() {
  let str = `I am a Super
  cool 
     programmer        
  . Some other things...`;

  const regex =  /[\s]+[\w]|^[\w]/g;

  str = str.replace(regex, (match) => {
    return match.toUpperCase();
  });

  console.log(str);
}

solve();

Output:

I Am A Super
  Cool 
     Programmer        
  . Some Other Things...

As you see, we kept all the tabs, line breaks, and spaces from the original string. We added a function as a second argument to replace() that passes the current ‘match’ of the RegEx, then we uppercased it.

Similar Posts