JavaScript正则表达式学习之定义(Regular Expression)

114 阅读2分钟
  1. 正则表达式是什么?

    是一种工具,是一个模式,在 JS 中也是一个对象。

    正则表达式是一些用来匹配和处理文本的字符串。

  2. 正则表达式能做什么?为什么要使用正则表达式?

    • 搜索——查找特定的信息

      // 查询文本文档有多少个span标签
      document.body.innerHTML.match(/<[Ss][Pp][Aa][Nn].*?>.*?</[Ss][Pp][Aa][Nn]>/g).length
      
    • 替换——查找并编辑特定的信息

      // 将文本文档中的p标签替换为自定义标签
      let str = document.body.innerHTML
      console.log(str.match(/<[Pp].*?>.*?</[Pp]>/g))
      const strRep = str.replace(/<[Pp](.*?)>(.*?)</[Pp]>/g, '<div1$1>$2</div1>')
      console.log(strRep.match(/<(div1).*?>.*?</\1>/g))
      
  3. 怎么使用正则表达式

    • 给定一个正则表达式,将需要操作的字符串与该模式进行匹配、或匹配并替换。

      // 匹配数字
      const reg = /\d{3}/
      reg.exec('abc123def')
      ​
      // 将css属性转为驼峰式命名 background-color -webkit-linear-gradient 转为backgroundColor webkitLinearGradient
      function dash2CamelCase (str) {
          return str.replace(/-([a-z])/g, function(match, capture1, index, input) {
              if (index === 0) {
                  return capture1
              }
              return capture1.toUpperCase()
          })
      }
      
  4. 正则表达式主要使用场景

    • 前端表单校验——校验用户输入的数据是否符合要求

      // 用户输入的邮箱是否正确
      const emailReg = /^\w+([.+-]\w+)*@\w+([.-]\w+)*.\w+([.-]\w+)*$/
      emailReg.exec('_123+abc-cde@163.com.cn')
      
    • 替换文本

      // 去除字符串首尾空格
      function trim (str) {
          return str.replace(/^\s*|\s*$/g, '')
      }
      trim(' 123 abc   ')
      
    • 提取子字符串

      // 捕获提取
      let str = 'https://www.runoob.com:80/regexp/regexp-syntax.html'
      let patt = /(\w+)://([^/:]+):?(\d*)?([^#]*)/
      str.match(patt)
      // split方法提取
      document.head.innerHTML.split(/(?<=<[Tt][Ii][Tt][Ll][Ee]>)(.*)(?=</[Tt][Ii][Tt][Ll][Ee]>)/)[1]
      
  5. 使用正则表达式之前需要注意的点

    • 在使用正则表达式的时候,往往有很多种方案。

      // 小于100的整数
      const numReg1 = /^[1-9]?[0-9]$/
      const numReg2 = /^(0|[1-9]\d?)$/
      
    • 为某个规则创建一个正则表达式不难,难点在于创建之前的那个规则是否已经考虑完善。

      // 匹配浮点数
      ^-?(0|[1-9][0-9]*).[0-9]*$
      // 上面的正则表达式可以匹配到0.00 或1.00之类的小数点后全部为0的情况
      // 完善一下规则,小数点后最后一位不能为0
      ^-?(0|[1-9][0-9]*).[0-9]*[1-9]$
      
    • 学习正则表达式最重要的点是实践,根据语法去读,去写。

    • 在把正则表达式运用到正式环境之前,请先在

      [正则表达式在线测试工具]  c.runoob.com/front-end/8… 

      上验证它的可行性。