-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex07.js
41 lines (32 loc) · 864 Bytes
/
ex07.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 isUpperCase(code) {
return (code >= 65 && code <= 90)
}
function snakeCase(str= ''){
let sentence = ''
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i)
if (code === 45) {
// Get rid of - from the beginning and ending of a string
continue
}
if (code === 32) {
// Replace spaces with -
sentence += "_"
} else if (isUpperCase(code)) {
if (i > 1) {
// Add - before uppercase
sentence += "_"
}
sentence += String.fromCharCode(code + 32)
} else {
sentence += str[i]
}
}
return sentence
}
console.log(snakeCase('gold d roger'))
// => 'gold_d_roger'
console.log(snakeCase('GoldDRoger'))
// => 'gold_d_roger'
console.log(snakeCase('-Gold-D-Roger-'))
// => 'gold_d_roger'