#29 转换驼峰命名


  • 0

    const toCamelCaseVar = (variable) => {
      return variable.replace(/_+[^_]/g, (...arg) => {
        if (arg[1]) {
          let rt = arg[0];
          return rt[rt.length - 1].toUpperCase();
        } else 
          return arg[0];
      });
    }
    

  • 0

    @Edge 0_1542770664009_upload-64d94c01-114c-4c68-87ca-b31db928baf3
    我也是提交报错


  • 0

    const toCamelCaseVar = (variable) => variable.replace(/([^_])(?:_+([^_]))/g, (match, p1, p2) => p1 + p2.toUpperCase())


  • 0

    一种方法:

    const toCamelCaseVar = (variable) = > {
      const reg = /^_*/;
      // 匹配字符串开头的_
      const start = variable.match(reg);
    
      // 两步替换,第一步将开头的_消除
      // 第二步将其余的_消除,后面紧跟的字符放在捕获组p1中,转换为大写
      let result = variable.replace(reg, '').replace(/_+(.)/g, (match, p1) = > p1.toUpperCase());
      
      // 如果之前消除过开头的_,需要加回来
      if (start && start.length > 0) {
        result = start[0] + result;
      }
      return result;
    };
    

    另一种方法:

    const toCamelCaseVar = (variable) => variable.replace(/([^_])(_+)(.)/g, (match, p1, p2, p3) => p1 + p3.toUpperCase());
    

  • 0

    const toCamelCaseVar = (variable) => variable.replace(/_+[a-zA-Z]/g,(m, i) => { return i ? (m.match(/[a-zA-Z]/)[0].toUpperCase()) : m})


  • 0

    @maroon 两个this


  • 0

    const toCamelCaseVar = (variable) => variable.replace(/_+[a-zA-Z]+?/g, (word, i) => i == 0 ? word : word.substring(word.length-1).toUpperCase())
    

  • 0

    貌似ScriptOJ不支持反向预查语法 (?<=...),首页拓展名那题也是,都会报错

    Invalid regular expression: /(?<=[^^]\w)_(\w)/: Invalid group

    本地测试下面这行是ok的
    const toCamelCaseVar = (variable) => variable.replace(/(?<=[^^]\w)\_(\w)/g, (p1) => p1.toUpperCase());


  • 0

    @沉默的张大爷 js 只支持正向预查, 你在 node 环境下跑的(V8)?


  • 0

    const toCamelCaseVar = (variable) => {
        return variable.replace(/_+(\S)/g, ($0, $1, $2) => {
            if ($2 !== 0)
                return $1.toUpperCase()
            else {
                return $0
            }
        })
    }
    

  • 0

    @lizhao 大佬牛逼, 这么熟练的吗


登录后回复
 

与 ScriptOJ 的连接断开,我们正在尝试重连,请耐心等待