Convert String to Camel Case in JavaScript

Convert String to Camel Case in JavaScript

Camel Case is a type of text format where the first letter of each word in a sentence is capitalized, and the remaining letters are lowercase. It is a very popular term in programming, because variables and functions are named in camel case format. For example, some examples of camel case - myVariableName or convertToCamelCase Here each new word is easy to understand, and the text is also shorter. In today's blog, we will discuss how to convert any string to camel case using JavaScript with detailed code and explanation, let's get started -

 

Problem - Convert string to camel case

 

Code and explanation


function toCamelCase(str) {
  return str
    .split(' ')                 // Splitting the string by spaces
    .map((word, index) => {
      if (index === 0) {
        return word.toLowerCase();  // Making the first word lowercase
      }
      return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();  // Capitalizing the first letter of subsequent words
    })
    .join('');  // Joining all the words together
}

// Example usage:
let sentence = "hello world from javascript";
let camelCaseString = toCamelCase(sentence);
console.log(camelCaseString);  // helloWorldFromJavascript

 

Code explanation

  • The split(‘ ’) method first splits the string on the basis of spaces and it creates an array where each word will be a separate element.
  • This map() method works on each element of the array (i.e. each divided word).
  • ToLowerCase() is used for the first word so that the first letter is lowercase.
  • To capitalize the first letter of the next word, charAt(0).toUpperCase() is used and to keep the rest lowercase, slice(1).toLowerCase() is used.
  • All the words are reassembled without any spaces through the join(‘’) method, resulting in camel case format and printed on the console.

 

Bookmark the website! If you like the post and don't forget to share the post so that your friends don't miss it. Be sure to like and comment so that we can constantly come up with new problems along with solutions and if you also have any coding-related problems, let us know in the comment box and we will try to solve them, InshaAllah.

About the author

Ahshan Habib
Hello! I am Ahshan Habib. I am a MERN Stack web developer. Blogging is my hobby and I would like to share my knowledge with everyone. Here I will share every day about education, technology, and Programming. So stay with us and share my page on your…

Post a Comment