正则截取/替换两个字符之间的字符串

正则表达式

  • 用来匹配字符串的一种规则表达式

创建正则对象

  • 构造函数
    • var reg = new RegExp(正则表达式,匹配模式);
    new RegExp(pattern,attributes);
    参数:参数pattern是一个字符串,指定了正则表达式的模式;
    参数attributes是一个可选的参数,包含属性 g(globle全局匹配),i(忽略大小写),m(多行匹配)
  • 字面量
    • var reg = /正则规则/匹配模式;

调用匹配方法

  • test 最常用 某个正则对象用来匹配某个字符串
    • 如果匹配成功,得到true,否则为false
    • 正则对象.test(字符串)
    例:匹配字符串中出出现连续的三个小写a
    var reg = new RegExp(/a{3}/);
    console.log(reg.test("aaac")); //true
    console.log(reg.test("baaab"));//true
    console.log(reg.test("aa"));//false
    console.log(reg.test("AAA"));//false
  • match 匹配某个字符串用
    • 字符串.match(正则表达式)
    • 返回值:数组 – 包含 匹配的字符串 匹配的索引 原来的字符串
    例:匹配字符串中是否包含连续的三个小写a
    console.log("aaabcdefaaaghjiy".match(/a{3}/));
  • exec
    • 匹配字符串用的
    • 正则对象.exec(字符串) 返回值跟match是一样的

截取/替换两个字符之间的字符串

const str = '/detail/page-1.html'
// 获取
str.match(/page-(\S*).html/)[1]
// 替换
str.replace(/(?<=page-).*?(?=.html)/, 2)

猜你喜欢

转载自blog.csdn.net/kiscon/article/details/119856593
今日推荐