-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
convert-pascalcase-string-into-snake-case.js
41 lines (33 loc) · 1.28 KB
/
convert-pascalcase-string-into-snake-case.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
function toUnderscore(string) {
if (typeof string !== 'string') return string.toString();
// use regex to match start with uppercase followed by 0 or more lowercase letters
const words = string.match(/[A-Z0-9][a-z0-9]*/g);
console.log(words);
// map over words to lowercase
const lowerCaseWords = words.map(word => word.toLowerCase());
console.log(lowerCaseWords);
// join on underscore
return lowerCaseWords.join('_');
}
function toUnderscore(string) {
if (typeof string !== 'string') return string.toString();
return string
.match(/[A-Z0-9][a-z0-9]*/g)
.map(word => word.toLowerCase())
.join('_');
}
function toUnderscore(string) {
if (typeof string !== 'string') return string.toString();
return string.replace(/[A-Z]/g, (letter) => '_' + letter.toLowerCase()).slice(1);
}
function toUnderscore(string) {
if (typeof string !== 'string') return string.toString();
return string.replace(/([A-Z])/g, '_$1').toLowerCase().slice(1);
}
// Alca
str => str.replace(/(?!^)([A-Z])/g, '_$1').toLowerCase()
console.log(toUnderscore('TestController'), 'test_controller');
console.log(toUnderscore('MoviesAndBooks'), 'movies_and_books');
console.log(toUnderscore('App7Test'), 'app7_test');
console.log(toUnderscore(1), '1');
// console.log(toUnderscore('1AbcDef'), '1');