How to convert a string to camel case in JavaScript?


Camel case is the practice of writing phrases such that each word or abbreviation in the middle of the phrase begins with a capital letter, with no intervening spaces or punctuation. For example, Concurrent hash maps in camel case would be written as −

ConcurrentHashMaps

We can implement a method to accept a string in JavaScript to convert it to camel case in the following way −

Example

function camelize(str) {
   // Split the string at all space characters
   return str.split(' ')
      // get rid of any extra spaces using trim
      .map(a => a.trim())
      // Convert first char to upper case for each word
      .map(a => a[0].toUpperCase() + a.substring(1))
      // Join all the strings back together
      .join("")
}
console.log(camelize("Concurrent hash maps"))

Output

ConcurrentHashMaps

Updated on: 19-Sep-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements