Javascript - Search
Knowing if something is or isn't in a string can be very important. If you have an online forum and don't want people to be able to create usernames that include swear words, you can use the search function to find bad words in usernames and reject them if any were found.
String Search Function
This string function takes a regular expression and then examines that string to see if there are any matches for that expression. If there is a match , it will return the position in the string where the match was found. If there isn't a match, it will return -1. We won't be going into great depth about regular expressions, but we will show you how to search for words in a string.
Search Function Regular Expression
The most important thing to remember when creating a regular expression is that it must be surrounded with slashes /regular expression/. With that knowledge let's search a string to see if a common name "Alex" is inside it.
JavaScript Search Function Regular Expression Code
<script type="text/javascript">
var myRegExp = /Alex/;
var string1 = "Today John went to the store and talked with Alex.";
var matchPos1 = string1.search(myRegExp);
if(matchPos1 != -1)
document.write("There was a match at position " + matchPos1);
else
document.write("There was no match in the first string");
</script>
JavaScript Search Function Regular Expression Display
There was a match at position 45
Notice:
that our regular expression was just the name "Alex". The search function then used this name to see if "Alex" existed in string1. A match was found, and the position of the match (45), was returned.
Another basic tool for regular expressions is the pipe character "|" (it's below the Backspace key on standard keyboards) which allows you to search for alternative words /RegExp1|RegExp2/. Instead of just searching for just one word, we can now use the pipe character to search for multiple words.
JavaScript Alternative Searches Code
<script type="text/javascript">
var myRegExp = /Alex|John/;
var string1 = "Today John went to the store and talked with Alex.";
var matchPos1 = string1.search(myRegExp);
if(matchPos1 != -1)
document.write("There was a match at position " + matchPos1);
else
document.write("There was no match in the first string");
</script>
JavaScript Alternative Searches Display
There was a match at position 6There was a match at position 6
Notice: that our regular expression had two names: Alex and John. The search function then used these names to try to find the first occurrence in the string string1. John came before Alex in our string, so its position (6), was returned.