/

HTML / CSS / JavaScript Tutorial

JavaScript String method: search()

[this page | pdf | back links]

The search() method (when applied to a JavaScript string) returns the position of the first occurrence of the search value (or -1, if no match is found).

 

It has the following syntax with the following parameters:

 

string.search(regexpression)

 

Parameter

Required / Optional

Description

regexpression

Required

Value (regular expression) to be searched for

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code><br></td>
<td><code id="Result"></code><br></td>
</tr>
</table>

<script>
var y = "abcde";
var z = "fg";
document.getElementById("Example").innerHTML =
  'var y = "' + y + '";<br>' +
  'var x = y.search("' + z + '");';
document.getElementById("Result").innerHTML = y.search(z);
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodStringSearch() {
  var z = "abc"; return !!z.search;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript String Variables


Desktop view | Switch to Mobile