Searching for text in strings with the search () method

When working with strings, sometimes there comes a need to determine if string contains some specific substring. In JavaScript, we can use the search () method to find substrings in a string. Suppose we have a string "JavaScript." And, let's say in that string we want to search for the string "Script." To perform this search, we will use the search () method. The search () method returns a number greater than or equal to 0 corresponding to the first occurrence of the substring if the substring ("Script") is found. If a substring is not found, the search () method returns -1.

The following shows the JavaScript code to perform the search using the search () method:

<script language="javascript">
var str, result;
str = "JavaScript";
result = str.search("Script");
document.write ("Substring found at position: " + result);
</script>

We perform the search on line 4. On line 4 we are searching for "Script" because this string is passed as an argument to the search () method. We search for that string in "JavaScript." Line 5 displays the result. We would expect a number 0 or greater because the string "Script" occurs first in "JavaScript." Because JavaScript starts counting at position 0 for an array, our string "Script" starts at position 4. See the following table to understand the corresponding position of each chracter in the string:

String J a v a S c r i p t
Position 0 1 2 3 4 5 6 7 8 9

The following shows the output from the JavaScript code: