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

How to use search() in javascript

青灯夜游
青灯夜游Original
2021-12-29 18:13:333965browse

In JavaScript, the search() method is used to retrieve a specified substring in a string, or to retrieve a substring that matches a regular expression, and returns the position of the first occurrence of the substring. The syntax "string .search(searchvalue)"; if no matching substring is found, "-1" is returned.

How to use search() in javascript

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

javascript search() method--search string

The search() method is used to retrieve the specified substring in the string, Or retrieve a substring that matches a regular expression.

Syntax:

string.search(searchvalue)

Parameter description:

  • ##searchvalue Required. The string or regular expression to search for.

Return value:

  • Returns the String object that matches the specified search string or regular expression. starting position.

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

Example:

Perform a case-sensitive search

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>

<p id="demo">单击显示查找的位置</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
	var str="Mr. Blue has a blue house"
	var n=str.search("blue");
	document.getElementById("demo").innerHTML=n;
}
</script>

</body>
</html>

How to use search() in javascript## Perform a case-ignoring search

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>

<p id="demo">单击显示查找的位置</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
	var str="Mr. Blue has a blue house"
	var n=str.search(/blue/i);
	document.getElementById("demo").innerHTML=n;
}
</script>

</body>
</html>

How to use search() in javascript[Related recommendations:

javascript learning tutorial

]

The above is the detailed content of How to use search() in javascript. 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