JS-字符串中和正则有关的方法

字符串方法

match

  • 唯一参数可以是正则字符串,也可以是RegExp对象。

    • 单个匹配:只匹配第一个,返回值是一个对象

      • 匹配成功,返回值是一个对象
      • 匹配失败,返回值是null
      let text = "cat, bat, sat, fat";
      let pattern = /.at/;
      
      let matches = text.match(pattern);  // 与patten.exec(text)结果一致
      console.log(matches);
      
      // 输入结果如下:
      {
          0: "cat",
          index: 0,
          input: "cat, bat, sat, fat",
          groups: undefined,
          length: 1
      }
      

      属性含义:

      • 0: 匹配上的字符串
      • 1: 第一个括号匹配的字符串(这里的正则没有括号,所以只有0)
      • 2: 第二个括号匹配的字符串
    • 全局匹配

      • 匹配成功,返回值是数组
      • 匹配失败,返回值是null
      let text = "cat, bat, sat, fat";
      let pattern = /.at/g;
      
      let matches = text.match(pattern);
      console.log(matches);
      
      // 输出结果如下:
      ["cat", "bat", "sat", "fat"]
      
  • 唯一参数可以是正则字符串,也可以是RegExp对象。是不是全局没区别

    • 匹配成功,返回值是第一个匹配成功的索引
    • 匹配失败,返回值是-1
    let text = "cat, bat, sat, fat";
    let pos = text.search(/at/);
    console.log(pos); // 1
    

replace

  • 参数

    • 第一个参数是RegExp对象或者字符串(不会转换成正则表达式)

    • 第二个参数可以是一个字符串或一个函数

  • 参数一为字符串时,只会替换第一个匹配的字符串;只有为全局模式的正则表达式,才能全局替换

    let text = "cat, bat, sat, fat";
    result = text.replace(/(.at)/g, "word ($1)");
    console.log(result); // word (cat), word (bat), word (sat), word (fat)
    
    let text = "cat, bat, sat, fat";
    result = text.replace(/(.at)/g, "word ($')");
    console.log(result); // word (, bat, sat, fat), word (, sat, fat), word (, fat), word ()
    

    有一些特殊的字符序列,可以用来插入正则表达式操作的值

image

  • 参数二是函数时

    • 只有一个匹配项,函数会有三个参数,与整个模式匹配的字符串、匹配项在字符串中的开始位置,以及整个字符串

image

function replacer(match, p1, p2, p3, offset, string, originalText) {
    return [p1, p2, p3].join('-');
}

let newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
console.log(newString); // abc-12345-#$*%

split

  • 参数一:字符串或RegExp
  • 参数二:数组长度,确保返回的数组不会超过指定大小
let colorText = "red,blue,green,yellow";
let colors1 = colorText.split(","); // ["red", "blue", "green", "yellow"]
let colors2 = colorText.split(",", 2); // ["red", "blue"]
let colors3 = colorText.split(/[^,]+/); // ["", ",", ",", ",", ""]
posted @ 2021-11-19 19:17  hmh12345  阅读(85)  评论(0)    收藏  举报