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

首先要了解这点:

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?"

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值