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;