How to use Array.map() and Array.join() In Javascript
In this approach first we split the string at hyphens (-) . Then using map() method we will iterate over each word in the array of substrings. For the first word (at index 0), no changes are made, For subsequent words, we will capitalized the first character and then concatenate with the rest of the word.
Example: This example shows the implementation of the above-explained approach.
function toCamelCase(str) {
return str
.split(/[-_]/)
.map((word, index) => {
if (index === 0) {
return word;
}
return (
word.charAt(0).toUpperCase() +
word.slice(1)
);
})
.join("");
}
console.log(toCamelCase("this_is_camel_case"));
Output
thisIsCamelCase
How to convert string to camel case in JavaScript ?
We will be given a string and we have to convert it into the camel case. In this case, the first character of the string is converted into lowercase, and other characters after space will be converted into uppercase characters. These camel case strings are used in creating a variable that has meaning.
Example of converting string to camel case in JavaScript
Table of Content
- Using the str.replace() method
- Using reduce() and split() method
- Using the Lodash _.camelCase() Method
- Using Array.map() and Array.join()
- Using a combination of String method
- Using Regex and Callback Function