出来混老是要还的-JS正则前传

前言: 正则表达式一直是我的痛点, 相信不少人 ( 说的就是你 ) 跟我同样存在相似的状况, 正则是反复学, 反复忘, 从我的角度看主要的缘由仍是:较少的使用场景, 若是像数组的几个经常使用方法同样, 绝大多数人确定能熟练运用。 最近迫使我拿起正则这把屠龙刀的原由是( 时间充足和一道小的面试题 ), 那我们就先从这道面试题提及javascript

Demo1

// 观察以下规律, 写一个函数`accum`
// accum("abcd"); // "A-Bb-Ccc-Dddd"
// accum("helloWorld"); // "H-Ee-Lll-Llll-Ooooo-Wwwwww-Ooooooo-Rrrrrrrr-Lllllllll-Dddddddddd"
// accum("China"); // "C-Hh-Iii-Nnnn-Aaaaa"
复制代码

看到题的第一反应就是, 握草这还不简单, 两层循环加上珍藏多年的字符串拼接技术(-_-||), 妥妥的解决这个问题java

const accum = str => {
  let result = "";
  str.toLowerCase().split("").forEach((el, idx) => {
      for (let i = 0; i <= idx; i++) {
        if (i == 0) {
          result += el.toUpperCase();
        } else {
          result += el;
        }
      }
      result += el + "-";
    });
  return result.slice(0, -1);
  // 看到slice慌不慌?是否是忘记这鬼东西是干什么的了?和substr/string有什么区别?
};
console.log(accum("CHina"));
复制代码

写完而且测试结果正确, 就开始沾沾自喜, 感受万事大吉。( 这种状态很像在工做中, 写完功能不去优化同样 )面试

上面的一坨代码, 对, 就是一坨代码, 一坨像极了业务功能的逻辑代码, 没有精巧的思路, 没有精致的写法。 这踏马跟咸鱼有什么区别?正则表达式

优雅的循环

const accum = str => {
  let result = "";
  for (let i = 0; i < str.length; i++) {
    const temp = str[i];
    result += temp.toUpperCase();
    for (let j = i; j > 0; j--) {
      result += temp.toLowerCase();
    }
    result += "-";
  }
  return result.slice(0, -1);
};
console.log(accum("CHina"));
复制代码

优雅的循环, 优雅的循环, 优雅的循环 啊、啊、啊!数组

精致的利己主义者

const accum = str => {
  return Array.from(str.toLowerCase(), (item, index) => {
    return (
      item.toUpperCase() + Array.from({length: index}, () => {
          return item;
        }
      ).join("")
    );
  }).join("-");
};
console.log(accum("CHina"));
复制代码

放荡不羁的 reduce

const accum = str => {
  return Array.from(str.toLowerCase()).reduce((accu, cur, idx) => {
      accu.push(cur.toUpperCase().padEnd(idx + 1, cur));
      return accu;
    }, []).join("-");
};
console.log(accum("CHina"));
复制代码

百辟匕首( RegExp )

匹配与获取字符串方法函数

const accum = str => {
  return str.toLowerCase().replace(/\w{1}/gi, (item, idx) => {
      let temp = "";
      Array.from(new Array(idx)).map(() => {
        temp += item;
      });
      return `${item.toUpperCase()}${temp}-`;
    }).slice(0, -1);
};
console.log(accum("CHina"));
复制代码

怎么样, 最后几种方案看的是否是很刺激、很惊喜, 其实就是一堆奇葩操做, 这是 API 操做者的狂欢, 也是 JS 开发者的基本功^_^post

这几个方案里面最使人惊喜的仍是 replace, 当第二个参数是一个函数, 当第一个参数为正则表达式而且为全局匹配模式时, 这个方法每次匹配都会被调用。测试

replace 应该是正则的 6 个经常使用 API 中最强大的一个, 它能够拿到你想要的信息, 而且假借替换之名, 作一些神奇操做优化

传送门 -> JS正则经常使用的有四种操做: 验证、切分、提取、替换ui

注:

  1. \w 匹配单词字符, 等价于[0-9a-ZA-Z_], 数字字母下划线
  2. {1} 连续出现 1 次

夯实基础

相关文章
相关标签/搜索