Skip to content

@utilslib/core/camelToSnake


将小驼峰命名转换为蛇形变量名称。


camelToSnake

函数签名

typescript
function camelToSnake(camelCase: string): string

描述

将小驼峰命名转换为蛇形变量名称。

参数

参数名类型可选默认值描述
camelCasestring--

返回值

string

示例

typescript
```js
camelToSnake('fooBar') // => 'foo_bar'
camelToSnake('fooBarBaz') // => 'foo_bar_baz'
camelToSnake('foo') // => 'foo'

::: details 点击查看源码
::: code-group
```js
/**
 * 将小驼峰命名转换为蛇形变量名称。
 *
 * @param {string} camelCase - 要转换的小驼峰命名字符串。
 * @returns {string} 转换后的蛇形变量名称。
 *
 * @example
 * \`\`\`js
 * camelToSnake('fooBar') // => 'foo_bar'
 * camelToSnake('fooBarBaz') // => 'foo_bar_baz'
 * camelToSnake('foo') // => 'foo'
 * \`\`\`
 */
export function camelToSnake(camelCase) {
  return camelCase.replace(/[A-Z]/g, function (match) {
    return `_${match.toLowerCase()}`;
  });
}
ts
/**
 * 将小驼峰命名转换为蛇形变量名称。
 *
 * @param {string} camelCase - 要转换的小驼峰命名字符串。
 * @returns {string} 转换后的蛇形变量名称。
 *
 * @example
 * \`\`\`js
 * camelToSnake('fooBar') // => 'foo_bar'
 * camelToSnake('fooBarBaz') // => 'foo_bar_baz'
 * camelToSnake('foo') // => 'foo'
 * \`\`\`
 */
export function camelToSnake(camelCase: string): string {
  return camelCase.replace(/[A-Z]/g, function (match) {
    return `_${match.toLowerCase()}`;
  });
}

:::

如有错误,请提交issue :::