Stringing Things Along - Search And Destroy (
Page 6 of 7 )
You can
also search for specific patterns in your strings with regular expressions, via
the String object's search() method. Here's an example:
<script language="JavaScript">
var str = "johndoe@somedomain.com";
var pattern =
/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/;
// returns 0
alert(str.search(pattern));
</script>
The search() method returns the
position of the substring matching the regular expression, or -1 if no match
exists.
You can also perform a search-and-replace operation with the
replace() method, which accepts both a regular expression and the value to
replace it with. Here's how:
<script language="JavaScript">
// set string
var str = "yo ho ho and a bottle of gum";
// returns "yo ho ho and a bottle of rum" alert(str.replace(/gum/gi,
"rum"));
</script>