Converting any string into camel case with JavaScript removing whitespace as well

JavascriptWeb DevelopmentObject Oriented Programming

In order to convert string into camel case, you need to lowercase the first letter of the word and the first letter of the remaining words must be in capital.

Following is the code to convert any string into camel case −

Example

function convertStringToCamelCase(sentence) {
   return sentence.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g,
   function(camelCaseMatch, i) {
      if (+camelCaseMatch === 0)
         return "";
      return i === 0 ? camelCaseMatch.toLowerCase() :
      camelCaseMatch.toUpperCase();
   });
}
console.log(convertStringToCamelCase("Add two variables"));

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo104.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo104.js
addTwoVariables
raja
Published on 07-Sep-2020 08:52:18
Advertisements