正则匹配:match()、test()函数区别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Hreticent/article/details/86374894

首先要了解这点:

match()函数是String对象的方法,参数是正则表达式,返回值是数组

test()函数是RegExp对象的方法,参数是字符串,返回值是boolean类型。

match()

举例一:

//test1
var name = 'zhangsan';
var a = name.match(/a/g);
console.log(a);//["a", "a"]

//test2
var name = 'zhangsan';
var a = name.match(/a/);
console.log(a);//["a"] 此a的index值为2,即若不全局匹配则返回第一个符合的值

举例二:

//判断日期类型是否为YYYY-MM-DD格式的类型    
function IsDate(str){     
  if(str.length!=0){    
    var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/;     
    var r = str.match(reg); 
    console.log(r);    
    if(r==null){   
      console.log('对不起,您输入的日期格式不正确!');                         
    }else{
      console.log('正确!'); 
    }
  }    
}   

IsDate("2019-01-12");
IsDate("20191-12");

test()

举例一

//判断输入的字符是否为中文    
 function IsChinese(str){     
    if(str.length!=0){    
        reg=/^[\u0391-\uFFE5]+$/;    
        if(!reg.test(str)){    
            console.log("对不起,您输入的字符串类型格式不正确!");
        }else{
            console.log("输入格式正确!");
        }
    }   
}    

IsChinese('你好阿!白兔仔');
IsChinese('hello,rabbit');

补充:

trim()    Remove the white spaces at the start and at the end of the string.

举例:

$.trim(" hello, how are you? ");//"hello, how are you?"

猜你喜欢

转载自blog.csdn.net/Hreticent/article/details/86374894