Skip to content

Commit 26af9cc

Browse files
committed
Add camelToSnakeCase
1 parent 228fcd1 commit 26af9cc

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

v-next/hardhat-utils/src/string.ts

+10
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,13 @@ export function capitalize(str: string): string {
4040
export function kebabToCamelCase(str: string): string {
4141
return str.replace(/-./g, (match) => match.charAt(1).toUpperCase());
4242
}
43+
44+
/**
45+
* Converts a camelCase string to snake_case.
46+
*
47+
* @param str The camelCase string to convert.
48+
* @returns The snake_case string.
49+
*/
50+
export function camelToSnakeCase(str: string): string {
51+
return str.replace(/[A-Z]/g, (match) => `_${match.toLowerCase()}`);
52+
}

v-next/hardhat-utils/test/string.ts

+17-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
import assert from "node:assert/strict";
22
import { describe, it } from "node:test";
33

4-
import { pluralize, capitalize, kebabToCamelCase } from "../src/string.js";
4+
import {
5+
pluralize,
6+
capitalize,
7+
kebabToCamelCase,
8+
camelToSnakeCase,
9+
} from "../src/string.js";
510

611
describe("string", () => {
712
describe("pluralize", () => {
@@ -44,4 +49,15 @@ describe("string", () => {
4449
);
4550
});
4651
});
52+
53+
describe("camelToSnakeCase", () => {
54+
it("Should convert a camelCase string to snake_case", () => {
55+
assert.equal(camelToSnakeCase("camelcasestring"), "camelcasestring");
56+
assert.equal(camelToSnakeCase("camelCaseString"), "camel_case_string");
57+
assert.equal(
58+
camelToSnakeCase("camelCASESTRING"),
59+
"camel_c_a_s_e_s_t_r_i_n_g",
60+
);
61+
});
62+
});
4763
});

0 commit comments

Comments
 (0)