All files / utils snake-case.ts

100% Statements 1/1
100% Branches 0/0
100% Functions 1/1
100% Lines 1/1

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18  189x                                
export function snakeCase(key: string) {
  return (
    key
      // Replace each space, dot, or hyphen with underscore
      .replace(/[.\s-]/g, "_")
      // Insert underscore between lowercase and uppercase letters
      .replace(/([a-z])([A-Z])/g, "$1_$2")
      // Insert underscore between digit and uppercase letter
      .replace(/([0-9])([A-Z])/g, "$1_$2")
      // Insert underscore between uppercase letters when followed by lowercase (for acronyms)
      .replace(/([A-Z])([A-Z][a-z])/g, "$1_$2")
      // Convert everything to lowercase
      .toLowerCase()
      // Remove underscores only from start and end of string
      .replace(/^_+|_+$/g, "")
  );
}