Member-only story
How to Convert Any String into Camel Case with JavaScript?
A tutorial on converting any string into a camel case with JavaScript.
Sometimes, we want to convert a JavaScript string into a camel case with JavaScript.
In this article, we’ll look at how to convert any string into a camel case with JavaScript.
Use the String.prototype.replace method
We can use the string instances’ replace
method to convert each word in the string to convert the first word to lower case, the rest of the words to upper case, then remove the whitespaces.
To do this, we write:
const camelize = (str) => {
return str.replace(/(?:^\w|[A-Z]|\b\w)/g, (word, index) => {
return index === 0 ? word.toLowerCase() : word.toUpperCase();
}).replace(/\s+/g, '');
}console.log(camelize("EquipmentClass name"));
We call replace
with a regex that looks for word boundaries with \b
and \w
.
\b
matches a backspace.
\w
matches any alphanumeric character from the Latin alphabet.
We check the index
to determine if it’s the first word or not.