JavaScript中String的search方法详解

String.prototype.search()

** String.prototype.search()方法为一个字符串对象执行一次正则表达式搜索。**

var paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

// []表示字符集合,\w表示任何字符,\s表示任何空格,^取反。因此这个模式会匹配任何一个不是字符且不是空格的字符,即本例中为匹配标点符号
var regex = /[^\w\s]/g;

console.log(paragraph.search(regex));
// 输出: 43

console.log(paragraph[paragraph.search(regex)]);
// 输出: "."”

语法

str.search(regexp)

参数

regexp
一个正则表达式对象。如果传递了一个非正则表达式对象,函数内部将会调用new RegExp(obj)把他转换成一个正则表达式对象。
返回值
如果查找成功,返回第一个被匹配到的值在字符串中的索引;否则返回-1。

描述

当你想知道一个字符串中是否存在一个模式,并且想知道这个匹配值得索引,就可以使用String.prototype.search()方法。如果你只是单纯的想知道一个模式是否存在于字符串,可以使用RegExp.prototype.test()方法,他会返回一个布尔值告诉你匹配模式是否存在。如果需要获取更多匹配信息,可以使用String.prototype.match()方法,或者相似的方法RegExp.prototype.exec()。查询效率:test()>search()>match()=exec()。

示例

使用String.prototype.search()匹配模式

下面的例子展示了String.prototype.search()方法的使用过程:

var str = "hey JudE";
var re1 = /[A-Z]/g;
var re2 = /[\.]/g;
console.log(str.search(re1)); // 返回4,即字母J的索引
console.log(str.search(re2)); // 返回-1,因为找不到.字符

你可能感兴趣的:(前端)