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