| Viewed 21 times

How to Convert String to camelCase in Javascript?


I need a function that converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized.

1 Answer
Mohammad Qandeel
Answered
0

This function will converts dash/underscore delimited words into camel casing

function toCamelCase(str) {
 let arr = str.split(/[-_]/);
 for(let i=1;i<arr.length;i++) {
  arr[i] = arr[i][0].toUpperCase() + arr[i].slice(1);
 }
 return arr.join('');
}

 

Output

toCamelCase('first-article') // "firstArticle"