JavaScript Objects: Finishing Strings - The Search() Method
(Page 3 of 6 )
There are a lot of ways to find out if a string holds a particular value, as you have already seen. Why not add another? The Search() method will find your value and return its position in the string, or -1 if it fails to find it.
<html>
<body>
<script type="text/javascript">
var who="Go Go Gorillas!"
document.write(who.search("go") + "<br />")
document.write(who.search("Go") + "<br />")
document.write(who.search("Gorilla") + "<br />")
</script>
</body>
</html>
This results in:
-1
0
6
Since the Search() method is case-sensitive, it returned a -1 when searching for the word "go." To remedy this situation, we simply add an “i” as in our previous programs and replace the quotation marks with forward slashes(/):
<html>
<body>
<script type="text/javascript">
var who="Go Go Gorillas!"
document.write(who.search(/go/i) + "<br />")
document.write(who.search("Go") + "<br />")
document.write(who.search("Gorilla") + "<br />")
</script>
</body>
</html>
This results in:
0
0
6
Next: The Slice() Method >>
More JavaScript Articles
More By James Payne