正则相关常用方法

108 阅读1分钟

正则相关常用方法

    1·test()    正则对象的方法
      正则表达式跟字符串进行匹配,匹配成功返回true,否则返回false
       
    2·search()   字符串对象方法
      返回匹配到的字符的索引号,没有匹配到返回-1
      
    3·match()    字符串对象方法
      匹配到的字符串存入数组返回
      
    4·replace    字符串对象方法
      用新字符替换匹配到的字符

test示例

    function test1() {
        let str = 'abcdef'
        let reg = /b/  //定义的正则表达式,匹字符串中是否有b这个字符
        let isSuccess = reg.test(str)
        if(isSUccess) {
            alert('匹配成功')
        } else {
            alert('匹配失败')
        }
    }
test1()


search示例

    function test2() {
        let str = 'abcedf'
        let reg = /b/ //定义定义的正则表达式,匹字符串中是否有b这个字符
        
        let index = str.search(reg)
        alert(index)
    }
test2()

match示例

    function test3(){
        let str = "dgfhfg254bhku289gdhydy674";
        let reg = /\b/  // /\b/表示0-9的数字,+ 至少一个数量
        let arr = str.match(reg)
        console.log(arr);
    }
test3()
    function test3(){
        let str = "dgfhfg254bhku289gdhydy674";
        let reg = /\b/g  // 加一个g表示全局,继续往后
        let arr = str.match(reg)
        console.log(arr);
    }
test3()

replace示例

    function test3() {
        let = 'aaa'
        //let reg = new RegExp('b') //构造函数方法
        let reg = /a/
        let newArr = str.replace(reg,'b') //正则匹配字符串,用新的字符串特换匹配到的字符串
        console.log(newArr);
    }