test、exec、match、replace、search

202 阅读1分钟
  1. test(),用于检测一个字符串是否匹配某个正则表达式,返回布尔值

     RegExpObject.test(string)
     var str1 = 'hello,monkey';
     var str2 = '你好,小猴子';
     console.log(/\w+/.test(str1)) // true
    console.log(/w+/.test(str2))  // false 
    
  2. exec(),用于检测一个字符串中正则表达式的匹配,返回一个数组或者null,存放匹配的结果

    RegExpObj.exec(string)
    console.log(/\w+/g.exec(str1)); //["hello",index:0,input:"hello,monkey"]
    
      
    

    test(),exec(),将字符串作为参数传入其中

  3. match(),在字符串中检测指定的值,或找到一个或多个正则表达式的匹配,返回数组或者null

    console.log(str1.match(/\w+/g));//返回 ["hello","monkey"]
    console.log(str2.mtch(/\w+/));// 未找到匹配,返回 null
    
  4. replace(),在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串,返回替换成功的字符串

    console.log(str1.replace('hello','hi'));// "hi,monkey"
    console.log(str2.replace(/hello/,'hi')); // 未匹配到被替换的内容,返回原字符串“你好,小猴子”
    console.log(str1.replace(/(\w+),(\w+)/,"$2,$1")); // 将字符交换位置,返回“monkey,hello”
    	
    
  5. search(),在字符串中检索指定的子字符串,或检索与正则表达式匹配的子串,返回第一个匹配的子串的起始位置

    console.log(str1.search(/\w+/)); //0
    console.log(str1.search(/\w+/g)); // 0 
    console.log(str2.search(/\w+/)); // -1
    

    match()、replace()、search() 将正则表达式作为函数参数传入其中