ReactHustle

How to Convert Camel Case to Snake Case in Javascript / Typescript

Jasser Mark Arioste

Jasser Mark Arioste

How to Convert Camel Case to Snake Case in Javascript / Typescript

Hello! In this tutorial, you'll learn how to convert camel case (camelCase) to snake case (snake_case) in javascript or Typescript.

What is camelCase? #

Camel case, also known as camelCase, is a naming convention used in programming and computer science for naming variables, functions, and sometimes other identifiers. It is characterized by the absence of spaces or punctuation and the use of capital letters to indicate the beginning of each new word within the identifier.

Here's how camel case works:

  1. The first word is written in lowercase.
  2. Each subsequent word within the identifier is capitalized, without any spaces or punctuation between them.

Camel case is commonly used in various programming languages, especially in languages like Java, JavaScript, C#, and Python for naming variables and functions. It's often used to make the names more readable and to distinguish words within an identifier.

What is snake_case? #

Snake case is another naming convention used in programming. In snake case, you separate words within an identifier by underscores (_) and typically use all lowercase letters. It's called "snake case" because the underscores look a bit like the scales on a snake.

Snake case is commonly used in programming languages like Python, Ruby, and some JavaScript projects for naming variables, functions, and file names.

Converting camelCase to snake_case #

Below is a function written in typescript that converts camelCase to snake_case:

export function camelToSnake(camelCaseStr: string): string {
  return camelCaseStr.replace(/[A-Z]/g, (match) => `_${match.toLowerCase()}`);
}

// Example usage:
const camelCaseStr = "myVar";
const snakeCaseStr = camelToSnake(camelCaseStr);
console.log(snakeCaseStr); // Output: "my_var"
12345678

This function takes a `camelCaseStr` as input and uses the `replace` method with a regular expression to find all uppercase letters (which represent the word boundaries in camelCase) and replace them with an underscore followed by the lowercase version of the letter. This effectively converts camelCase to snake_case.

You can use this function to convert camelCase strings to snake_case as needed in your TypeScript code.

Extending String.prototype #

If you want to use camelToSnake function as an extension of the string functions like replacetoUpperCase, toLowerCase, etc., you can extend the String.prototype object.

//utils/camelToSnake.ts
declare global {
  // use augmentation to create a new function declaration for the string interface
  interface String {
    camelToSnake(): string;
  }
}

//override camelToSnake function if it isn't defined
if (!String.prototype.camelToSnake) {
  String.prototype.camelToSnake = function (): string {
    return this.toString().replace(
      /[A-Z]/g,
      (match) => `_${match.toLowerCase()}`
    );
  };
}

//make this file a module
export {};
1234567891011121314151617181920

To use this, you can do the following:

// index.ts
import "utils/camelToSnake.ts";
const camelCaseString = "myVariableName";
const snakeCaseString = camelCaseString.camelToSnake();
console.log(snakeCaseString); // Output: "my_variable_name"
12345

Once imported, you can use the `camelToSnake` function for all string instances.

Conclusion #

You learned common naming conventions camel case and snake case. You also learned how to convert camelCase to snake case using the String.prototype.replace function. In addition, you learned how to extend String.prototype to be able to use the camelToSnake function for all string instances.

Resources #

To learn more about string.replace, you can go to its documentation.

Credits: Image by Manfred Antranias Zimmer from Pixabay

Share this post!

Related Posts

Disclaimer

This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle