[前端] js正则表达式及几个常用的正则模式

js正则表达式
 

一、使用new RegExp()对象

new RegExp(pattern, attributes);
参数 pattern 是一个字符串,指定了正则表达式的模式或其他正则表达式。

参数 attributes 是一个可选的字符串,包含属性 "g"、"i" 和 "m",分别用于指定全局匹配、区分大小写的匹配和多行匹配。ECMAScript 标准化之前,不支持 m 属性。如果 pattern 是正则表达式,而不是字符串,则必须省略该参数。
 
var pattern = new RegExp('e');

 

定义一个模式,这个模式用来查找匹配字符e的字串
 
1、使用test()方法,检索字符串中的指定值。返回值是 true 或 false。
console.log(pattern.test('hello'));  // true

 

2、使用exec()方法,检索字符串中的指定值。返回值是被找到的值。如果没有发现匹配,则返回 null。
console.log(pattern.exec('hello'));  // ["e", index: 1, input: "hello"]

 

3、compile()方法
1)、用于改变 RegExp。
2)、既可以改变检索模式,也可以添加或删除第二个参数。
pattern.compile('o');
console.log(pattern.exec('hello'));  // ["o", index: 4, input: "hello"]

 

二、使用使用简写模式,不用实例对象new RegExp() 

 
1、search()方法 返回字符串第一个匹配到字符e的索引位置,如果没有匹配到则返回-1
console.log('hello'.search(/e/));  // 1

 

2、match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配,如果没有匹配到返回null。

该方法类似 indexOf() 和 lastIndexOf(),但是它返回指定的值,而不是字符串的位置。

var str="1 plus 2 equal 3";
console.log(str.match(/\d+/g));  // ["1", "2", "3"]  或 /\d\w/g 也可以

 

3、replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。
var str="Visit Microsoft!";
console.log(str.replace(/Microsoft/, "W3School"));  // Visit W3School!

 

 

三、常用正则表达式:

验证数字:^[0-9]*$

 

var pattern = /^[0-9]*$/;
console.log(pattern.test('135'));  // true

验证n位的数字:^\d{n}$

 

 

var pattern = /^\d{3}$/;
console.log(pattern.test('123'));  // true

验证至少n位数字:^\d{n,}$

 

 

var pattern = /^\d{3,}$/;
console.log(pattern.test('12'));  // false

验证m-n位的数字:^\d{m,n}$

 

 

var pattern = /^\d{3,5}$/;
console.log(pattern.test('345'));  // true

验证长度为3的字符:^.{3}$

 

 

var pattern = /^.{3}$/;
console.log(pattern.test('acc'));  // true

验证由26个英文字母组成的字符串:^[A-Za-z]+$

 

 

var pattern = /^[A-Za-z]+$/;
console.log(pattern.test('acc'));  // true

验证由数字和26个英文字母组成的字符串:^[A-Za-z0-9]+$

 

 

var pattern = /^[A-Za-z0-9]+$/;
console.log(pattern.test('acc123'));  // true

 


验证由数字、26个英文字母或者下划线组成的字符串:^\w+$

 

var pattern = /^\w+$/;
console.log(pattern.test('_acc123'));  // true

 

 

其他实用的验证,请参照 http://blog.csdn.net/u010081689/article/details/50340881 验证电话号码、身份证号、中文名称

欢迎关注技术开发分享录:http://fenxianglu.cn/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天空还下着雪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值