Skip to content
the poor coder

snake_case to camelCase in javascript

Poor Man
Published
Reading time
1 min read
On this page

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:

Text

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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC