JS正则表达式完全匹配字符

js中 RegExp 对象使用 test() 来匹配正则表达式时,只要有子字符串能够匹配成功就会返回 true。

如果要当正则表达式完全匹配整个字符串时 test() 才返回true的话,可以在正则表达式的开头加入^ (表示开头),结尾加入$(表示结尾)。

var reg1 = /12345678/;
var reg2 = /^12345678$/;
​
var test1 = "12345678";
var test2 = "0123456789";
​
console.log(reg1.test(test1));      //true
console.log(reg1.test(test2));      //true
console.log(reg2.test(test1));      //true
console.log(reg2.test(test2));      //false

若想完整匹配一个单词,可以使用以下形式:

var reg2 = /\bword\b/;
var reg3 = /(?:^|(\s))word(?:$|\s)/;

其中 reg2 的正则表达式会匹配以 "-" 、"." 和其他的字符(没有一一去测)分隔的单词

而 reg3 的正则表达式只会匹配以空白字符分隔的单词

var testStr4 = "word";
var testStr5 = "wordwithoutspace";
var testStr6 = "a word with space";
var testStr7 = "a-word-with-strikethrough";
var testStr8 = "a0word0with0number";
var testStr9 = "a_word_with_underline";
var testStr10 = "a.word.with.decimal";
var testStr11 = "a  word    with    tab";

var reg2 = /\bword\b/;
console.log("reg2.test(testStr4)",reg2.test(testStr4));     //true
console.log("reg2.test(testStr5)",reg2.test(testStr5));     //false
console.log("reg2.test(testStr6)",reg2.test(testStr6));     //true
console.log("reg2.test(testStr7)",reg2.test(testStr7));     //true
console.log("reg2.test(testStr8)",reg2.test(testStr8));     //false
console.log("reg2.test(testStr9)",reg2.test(testStr9));     //false
console.log("reg2.test(testStr10)",reg2.test(testStr10));   //true
console.log("reg2.test(testStr11)",reg2.test(testStr11));   //true

console.log()
var reg3 = /(?:^|(\s))word(?:$|\s)/;
console.log("reg3.test(testStr4)",reg3.test(testStr4));     //true
console.log("reg3.test(testStr5)",reg3.test(testStr5));     //false
console.log("reg3.test(testStr6)",reg3.test(testStr6));     //true
console.log("reg3.test(testStr7)",reg3.test(testStr7));     //false
console.log("reg3.test(testStr8)",reg3.test(testStr8));     //false
console.log("reg3.test(testStr9)",reg3.test(testStr9));     //false
console.log("reg3.test(testStr10)",reg3.test(testStr10));   //false
console.log("reg3.test(testStr11)",reg3.test(testStr11));   //true

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值