Searching for Text in Strings

Searching for Text in Strings

When working with text strings, sometimes you need to determine if a string contains some specific substring, and if it does, you need to determine where in the string that substring occurs. The search() method searches for a match between a regular expression and a string. This method returns the position of the match, or -1 if no match is found.

Syntax

string.search(regexp)

For instance, if you have the string “what is happening here” and you search for the substring “is”, you want to know that the string contains “is” but also where “is” occurs. You can perform this type of search with the search method of the string object.
testVariable.search(“is”);
This method returns a numeric value indicating the position in the string where it found “is”. In this case, that position is 5.

Example:

<body>
<script language="JavaScript">
<!--
var myVariable = "Hello there";
var therePlace = myVariable.search("there");
document.write(therePlace);
// -->
</script>
</body>
DOWNLOAD SOLUTION HERE