【问题标题】:Transform a string from camel case to snake case and vice versa将字符串从骆驼格转换为蛇格,反之亦然
【发布时间】:2019-05-06 12:22:01
【问题描述】:

我想将大写字符串转换为带下划线的字符串,例如:

 - "blablaBlabla" to "blabla_blabla" 
 - "firstName" to "first_name" 

反之亦然:

 - "blabla_blabla" to "blablaBlabla"
 - "first_Name" to "firstName"

我使用 Typescript,但我认为这与 Javascript 没有区别。

提前致谢。

杰里米。

【问题讨论】:

  • 到目前为止你尝试过什么?
  • 提示:有用的搜索词是“camel cast”和“snake case”
  • This question 要求相反的操作,但过程将是相同的:使用正则表达式匹配_ 和您放入捕获组的以下字母,提取该捕获组的内容,翻译成大写,用大写替换匹配项。

标签: javascript string algorithm typescript


【解决方案1】:

[A-Z]replace 可以得到所有大写字母,_ + m.toLowerCase() 匹配

要以另一种方式更改它,匹配所有_([a-z]) 以将字母表添加到捕获组。然后在捕获时使用toUpperCase

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案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()}`;
          });
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-05-15
        • 1970-01-01
        • 2011-05-27
        • 1970-01-01
        • 2013-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多