Skip to content
Advertisement

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.

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement