This post will discuss how to convert the first letter of every word in a string uppercase in JavaScript.

There are several ways to capitalize the first letter of every word in a string in JavaScript. Here are some of the most common functions, along with some examples and explanations:

1. Using split(), map(), and join() functions

The idea is to split the string into an array of words with split(), then map every word to a function that capitalizes its first letter and returns the rest unchanged using map(), and finally joining the array back into a string using join() function. Here’s an example:

Download  Run Code

2. Using replace() function

This approach involves using a regular expression to match the first letter of every word in the string, and then replacing it with its uppercase version. For example, we can use the regular expression /^\w|\b\w/g to capitalize the first letter of every word in the string. The regex matches any word character (\w) that is either at the start of the string (^) or after a word boundary (\b). The g modifier makes the match global, so it applies to all words in the string.

Download  Run Code

3. Using charAt() and slice() functions

The idea here is to use a loop to iterate over every word in the string, and then using the charAt() function to access the first letter of every word and make it uppercase, and the slice() or the substring() function to get the rest of the word unchanged. Then, it concatenates the uppercase version of the first letter with the rest of the word. Here’s an example:

Download  Run Code

That’s all about converting the first letter of every word in a string uppercase in JavaScript.