snake_case to camelCase in javascript

Converting snake_case to camelCase in JavaScript

If you have worked with JavaScript for some time, you must have come across variable names in snake_case format. However, it is important to note that camelCase is a preferred naming convention in JavaScript. In this article, we will discuss how to convert snake_case to camelCase format in JavaScript.

Method 1: Using replace() method and Regular Expressions

One way to convert snake_case to camelCase is by using the replace() method, along with regular expressions. Here's the code:


let snakeCaseVariable = 'my_variable_name';
let camelCaseVariable = snakeCaseVariable.replace(/_([a-z])/g, function (g) { return g[1].toUpperCase(); });
console.log(camelCaseVariable); // Output: myVariableName
  

Method 2: Using split() and join() methods

Another way to convert snake_case to camelCase is by using the split() and join() methods. Here's the code:


let snakeCaseVariable = 'my_variable_name';
let camelCaseVariable = snakeCaseVariable.split('_').map(function(word, index) {
  // If it's the first word, keep it lowercase
  if (index === 0) {
    return word;
  }
  // If it's not the first word, capitalize the first letter and join with the rest of the word
  return word.charAt(0).toUpperCase() + word.slice(1);
}).join('');
console.log(camelCaseVariable); // Output: myVariableName
  

Conclusion

These are two ways to convert snake_case to camelCase in JavaScript. It is important to choose a naming convention and stick to it throughout your codebase, for consistency and readability purposes.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe