Detailed explanation of the search method of String in JavaScript

String.prototype.search()

** The String.prototype.search() method performs a regular expression search for a string object. **

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)]);
// 输出: "."”

grammar

str.search(regexp)

parameter

regexp
A regular expression object. If a non-regular expression object is passed, the function will call new RegExp(obj) to convert it into a regular expression object.
Return Value
If the search is successful, returns the index of the first matched value in the string; otherwise returns -1.

describe

When you want to know whether a pattern exists in a string, and you want to know that this match is worth indexing, you can use the String.prototype.search() method. If you simply want to know if a pattern exists in the string, you can use the RegExp.prototype.test() method, which will return a boolean value telling you whether the matching pattern exists. If you need to get more matching information, you can use the String.prototype.match() method, or the similar method RegExp.prototype.exec(). Query efficiency: test()>search()>match()=exec().

example

Use String.prototype.search() to match patterns

The following example shows the use of the String.prototype.search() method:

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,因为找不到.字符

Guess you like

Origin blog.csdn.net/yuhk231/article/details/88191535