📜  javascript to camelcase - Javascript (1)

📅  最后修改于: 2023-12-03 15:01:38.960000             🧑  作者: Mango

JavaScript to CamelCase

When working with JavaScript, sometimes you may come across variable or function names that use "snake_case" or "kebab-case" instead of "CamelCase". However, many JavaScript frameworks and libraries prefer or even require the use of CamelCase. Therefore, it is important to know how to convert variable or function names from snake_case or kebab-case to CamelCase in JavaScript.

Method 1: Manual Conversion

The easiest way to manually convert a snake_case or kebab-case string to CamelCase is to split the original string into an array of words, capitalize the first letter of each word except the first one, and then join the words back together into a single string. Here is an example code snippet in JavaScript:

function snakeToCamel(str) {
  let words = str.split('_');
  let result = words[0];
  for(let i = 1; i < words.length; i++) {
    result += words[i].charAt(0).toUpperCase() + words[i].slice(1);
  }
  return result;
}

function kebabToCamel(str) {
  let words = str.split('-');
  let result = words[0];
  for(let i = 1; i < words.length; i++) {
    result += words[i].charAt(0).toUpperCase() + words[i].slice(1);
  }
  return result;
}

console.log(snakeToCamel('hello_world')); // outputs: "helloWorld"
console.log(kebabToCamel('hello-world')); // outputs: "helloWorld"
Method 2: Regular Expression Conversion

If you have a lot of variable or function names to convert, you can use regular expressions to automate the process. Here is an example code snippet in JavaScript:

function snakeToCamel(str) {
  return str.replace(/_([a-z])/g, function(match, letter) {
    return letter.toUpperCase();
  });
}

function kebabToCamel(str) {
  return str.replace(/-([a-z])/g, function(match, letter) {
    return letter.toUpperCase();
  });
}

console.log(snakeToCamel('hello_world')); // outputs: "helloWorld"
console.log(kebabToCamel('hello-world')); // outputs: "helloWorld"

In the regular expressions, we use a capturing group ([a-z]) and replace it with its uppercase version. The letter is identified using the letter parameter in the callback function.

In conclusion, converting variable or function names from snake_case or kebab-case to CamelCase is an important task in JavaScript development. By using the above methods, you can easily convert names to meet the required naming conventions.