'Transform a string from camel case to snake case and vice versa
I would like transform string with uppercase to string with underscore like :
- "blablaBlabla" to "blabla_blabla"
- "firstName" to "first_name"
And conversely :
- "blabla_blabla" to "blablaBlabla"
- "first_Name" to "firstName"
I use Typescript, but I think for that, there is no difference with the Javascript.
Thank's in advance.
Jérémy.
Solution 1:[1]
let word = "firstName";
let output = "";
// for conversion
for (let i = 0; i < word.length; i++) {
if (word[i] === word[i].toUpperCase()) {
output += "_" + word[i].toLowerCase();
} else {
output += word[i];
}
}
console.log(output);
let source = output;
output = "";
//for reversion
for (let i = 0; i < source.length; i++) {
if (source[i] === "_") {
i++;
output += source[i].toUpperCase();
} else {
output += source[i];
}
}
console.log(output);
Solution 2:[2]
You could get all the upper case letters with [A-Z]
and replace
the match with _ + m.toLowerCase()
To change it the other way, match all _([a-z])
to get the alphabet to a capturing group. And then use toUpperCase
on the capture
function trasnform1(str) {
return str.replace(/[A-Z]/g, (m) => '_' + m.toLowerCase())
}
function trasnform2(str) {
return str.replace(/_([a-z])/g, (m, p1) => p1.toUpperCase())
}
console.log(trasnform1("blablaBlabla"))
console.log(trasnform1("firstName"))
console.log(trasnform2("blabla_blabla"))
console.log(trasnform2("first_name"))
Solution 3:[3]
// Camel to snake and snake to camel case
function changeCasing(input) {
if (!input) {
return '';
}
if (input.indexOf('_') > -1) {
const regex = new RegExp('_.', 'gm');
return input.replace(regex, (match) => {
const char = match.replace("_", "");
return char.toUpperCase();
});
} else {
const regex = new RegExp('[A-Z]', 'gm');
return input.replace(regex, (match) => {
return `_${match.toLowerCase()}`;
});
}
}
Solution 4:[4]
This is example written in TypeScript. It's more readable using method chaining.
export const snake2Camel = (snake: string): string => {
return snake.split('').reduce((prev: string, cur: string) => {
if (prev.includes("_")) {
prev = prev.substring(0, prev.length - 1);
cur = cur.toUpperCase();
}
return prev + cur;
}, "");
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | adiga |
Solution 2 | |
Solution 3 | Chirag |
Solution 4 | micheal_ko |