I would like transform string with uppercase to string with underscore like :
JavaScript
x
3
1
- "blablaBlabla" to "blabla_blabla"
2
- "firstName" to "first_name"
3
And conversely :
JavaScript
1
3
1
- "blabla_blabla" to "blablaBlabla"
2
- "first_Name" to "firstName"
3
I use Typescript, but I think for that, there is no difference with the Javascript.
Thank’s in advance.
Jérémy.
Advertisement
Answer
JavaScript
1
26
26
1
let word = "firstName";
2
let output = "";
3
4
// for conversion
5
for (let i = 0; i < word.length; i++) {
6
if (word[i] === word[i].toUpperCase()) {
7
output += "_" + word[i].toLowerCase();
8
} else {
9
output += word[i];
10
}
11
}
12
console.log(output);
13
14
let source = output;
15
output = "";
16
17
//for reversion
18
for (let i = 0; i < source.length; i++) {
19
if (source[i] === "_") {
20
i++;
21
output += source[i].toUpperCase();
22
} else {
23
output += source[i];
24
}
25
}
26
console.log(output);