How to use the underscore function from inflection

Find comprehensive JavaScript inflection.underscore code examples handpicked from public code repositorys.

In JavaScript, inflection.underscore is a function in the Inflection library that converts a string from camelCase or PascalCase to snake_case.

95
96
97
98
99
100
101
102
103
104
105
106
  return str.trim().replace(/[-_\s]+(.)?/g, (match, c) => c.toUpperCase());
}
exports.camelize = camelize;


function underscore(str) {
  return inflection.underscore(str);
}
exports.underscore = underscore;


function singularize(str) {
fork icon0
star icon3
watch icon0

How does inflection.underscore work?

inflection.underscore is a function in the Inflection library for JavaScript that converts a string from camelCase or PascalCase to snake_case.

When inflection.underscore is called with a string as input, it performs the following operations:

  • It converts the input string to lowercase.
  • It replaces any uppercase letters with a lowercase letter followed by an underscore.
  • It removes any non-alphanumeric characters from the string.

For example, if we called inflection.underscore with the string "camelCaseString", it would return "camel_case_string". If we called it with "PascalCaseString", it would return "pascal_case_string". Note that inflection.underscore assumes that the input string is already in camelCase or PascalCase, so it may not produce the desired output if the input string has a different format.

By using inflection.underscore, developers can easily convert strings from camelCase or PascalCase to snake_case, which can be useful for conforming to naming conventions in APIs, databases, and other contexts where snake_case is preferred.

Ai Example

1
2
3
4
5
6
const inflection = require("inflection");

const camelCaseString = "camelCaseString";
const underscoreString = inflection.underscore(camelCaseString);

console.log(underscoreString); // Outputs: "camel_case_string"

In this example, we're using inflection.underscore to convert a string from camelCase to snake_case. We provide the input string "camelCaseString" as input to inflection.underscore, which returns "camel_case_string". We then log the result to the console. Note that inflection.underscore can also be used to convert strings from PascalCase to snake_case by simply passing a PascalCase string as input instead of a camelCase string.