简体   繁体   English

将字符串从骆驼大小写转换为蛇形大小写,反之亦然

[英]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.我用的是Typescript,不过我觉得和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()您可以使用[AZ]获取所有大写字母,并使用_ + m.toLowerCase() replace匹配项

To change it the other way, match all _([az]) to get the alphabet to a capturing group.要以另一种方式更改它,请匹配所有_([az])以将字母表添加到捕获组中。 And then use toUpperCase on the capture然后在捕获上使用toUpperCase

 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.这是在 TypeScript 中编写的示例。使用方法链接更具可读性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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