JavaScript中RegExp的test方法详解

RegExp.prototype.test()

** RegExp.prototype.test()方法为指定正则表达式和指定字符串执行一次匹配,返回true或false。**

var regex1 = RegExp('foo*');
var regex2 = RegExp('foo*','g');
var str1 = 'table football';

console.log(regex1.test(str1));
// 输出: true

console.log(regex1.test(str1));
// 输出: true

console.log(regex2.test(str1));
// 输出: true

console.log(regex2.test(str1));
// 因为g修饰符的存在,lastIndex改变,输出: false

语法

regexpObj.test(str)

参数

str
需要匹配模式的字符串。

返回值

如果匹配成功,返回true。否则返回false。

描述

如果想知道一个字符串中是否存在一个模式,调用test()函数即可。不像String.prototype.search()返回匹配项的索引,RegExp.prototype.test()函数只返回一个布尔值。如果想要获取更多信息,调用RegExp.prototype.exec()函数或String.prototype.match()函数,但是这两个函数的执行效率会低于RegExp.prototype.test()函数。RegExp.prototype.exec()和RegExp.prototype.test一样,在设置了g修饰符之后,每次执行都会设置lastIndex,从而影响下一次匹配的结果。

示例

使用RegExp.prototype.test()

下面代码查找一个字符串中是否以”hello”开头:

var str = 'hello world!';
var result = /^hello/.test(str);
console.log(result); // true

在一个包含g修饰符的正则上使用RegExp.prototype.test()函数

如果正则表达式被设置了g修饰符,RegExp.prototype.test()函数会在每一次调用后设置正则表达式的lastIndex值。在其后调用的test()会从这个lastIndex索引位置开始匹配(RegExp.prototype.exec()函数也遵循同样的规则)。如果前后传入不同的字符串作为参数,RegExp.prototype.test()的结果就是没有意义的。
下面的代码展示了这些特性:

var regex = /foo/g;

// regex.lastIndex = 0
regex.test('foo'); // true

// regex.lastIndex = 3
regex.test('foo'); // false

// regex.lastIndex = 0
regex.test('barfoo') // true

// regex.lastIndex = 6
regex.test('foobar') //false

利用这种机制,下面的代码建立了一个函数,用来查找在一个字符串中一共有多少单词:

function countWords (sText) {

  for (var rWord = /\w+/g, nCount = 0; rWord.test(sText); nCount++);

  return nCount;

}

console.log(countWords("What a beautiful day!")); // 4

猜你喜欢

转载自blog.csdn.net/yuhk231/article/details/88191380