Home  >  Article  >  Web Front-end  >  How to use javascript search() method

How to use javascript search() method

青灯夜游
青灯夜游Original
2021-06-22 17:33:251735browse

search() is a method built into javascript. It is mainly used to retrieve the specified substring in the string, or to retrieve the substring matching the regular expression. Find and return the first string in the specified string. The position of the first occurrence, syntax "string.search(match pattern)".

How to use javascript search() method

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

The search() method is used to retrieve a specified substring in a string, or to retrieve a substring that matches a regular expression, and find and return the first occurrence of the specified string.

If no matching substring is found, -1 is returned.

Syntax

string.search(searchvalue)

The search() method has only one parameter, which defines the matching pattern and specifies the string or regular expression to search for.

Return value: Number type, the starting position of the String object that matches the specified search string or regular expression.

Example:

The following code uses the search() method to match the slash character at the subscript position of the URL string.

var s = "c.biancheng.net";
n="s.search("//");"

search() method parameter definition:

  • The parameter of the search() method is a regular expression (RegExp object). If the argument is not a RegExp object, JavaScript converts it to a RegExp object using the RegExp() function.

  • The search() method follows the search order from left to right and returns the starting subscript position value of the first matching substring. If not found, -1 is returned.

  • The search() method cannot search the specified range and always returns the subscript value of the first matching substring, which is not as flexible as the indexOf() method.

[Related recommendations: javascript learning tutorial]

The above is the detailed content of How to use javascript search() method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn