Categories
JavaScript Answers

How to Convert Any String into Camel Case with JavaScript?

Spread the love

Sometimes, we want to convert a JavaScript string into camel case with JavaScript.

In this article, we’ll look at how to convert any string into 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.

If it’s 0, then we return word.toLowerCase() to convert it first character of the word to lower case since it’s the first word.

Otherwise, we return word.toUpperCase to convert the first character of the word to upper case.

Then we call replace again with /\s+/g and an empty string to replace the spaces with empty strings.

Therefore, camelize returns 'equipmentClassName’ as a result.

Lodash camelCase Method

We can use the Lodash camelCase method to convert any string to camel case the same way the camelize function does.

For instance, we can write:

console.log(_.camelCase("EquipmentClass name"));

Then we get the same result as the previous example.

Conclusion

We can convert any JavaScript string to camel case with the String.prototype.replace method or the Lodash camelCase method.

Leave a Reply

Your email address will not be published. Required fields are marked *