How to convert a string into a camel case in JavaScript
📅April 1, 2022
Today we will show you how to convert a string into a camel case in JavaScript. There are many methods for converting a string to a camelCase, but we'll look at two of them.
Checkout more articles on JavaScript
- Reverse a String in JavaScript
- Automatically refresh or reload a page using JavaScript
- Capitalize the first letter of a string using JavaScript
- How to search an array in JavaScript
- Scroll to a specific element using JavaScript
Convert a string into a camel case
1. Using regular expression
In this method, we’ll use the Regular Expression, `toLowerCase()` and `toUpperCase()` methods to convert a string into a camel case.
function camelCase(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
return index === 0 ? match.toLowerCase() : match.toUpperCase();
});
}
camelCase("Clue mediator"); // Output: clueMediator
camelCase("hello world"); // Output: helloWorld
2. Using lodash
In this second method, we will use the `camelCase()` function from the lodash. Don’t forget to add the lodash script in the page.
camelCase("Clue mediator"); // Output: clueMediator
camelCase("hello world"); // Output: helloWorld
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂