String Method: Search

The two methods, indexOf() and search(), are equal. They accept the same arguments (parameters), and they return the same value. However, the search() method can take much more powerful search values.The search() method searches a string for a specified value (a string in a string) and returns the position of the match. In this example, the quotation marks used to define the variable locally are not counted, (as they are when defined globally):

HTML file: Displayed by browser:
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo">Find with indexOf() - versus - Search with search()</p>
<script>
function myFunction() {
    var str = "Please locate where 'locate' occurs!";
    var pos = str.search("locate");
    document.getElementById("demo").innerHTML = pos;
}
</script>
</body>

Find with indexOf() - versus - Search with search()

More about powerful search values in the chapter about regular xpressions.

BackTable of ContentsNext