简体   繁体   中英

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.

You could get all the upper case letters with [AZ] and replace the match with _ + m.toLowerCase()

To change it the other way, match all _([az]) to get the alphabet to a capturing group. And then use toUpperCase on the capture

 function trasnform1(str) { return str.replace(/[AZ]/g, (m) => '_' + m.toLowerCase()) } function trasnform2(str) { return str.replace(/_([az])/g, (m, p1) => p1.toUpperCase()) } console.log(trasnform1("blablaBlabla")) console.log(trasnform1("firstName")) console.log(trasnform2("blabla_blabla")) console.log(trasnform2("first_name"))

 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);

// 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()}`;
    });
  }
}

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;
  }, "");
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM