Stringing Things Along - Building Character (Page 5 of 7 )
You can use the indexOf() method to locate the first occurrence of a particular set of characters in a string
<script language="Javascript">
// set string
var str = "It's a bird! It's a plane! It's Superman!";
// returns 5
alert(str.indexOf("a"));
</script>and the lastIndexOf() method to locate its
last occurrence.
<script language="Javascript">
// set string
var str = "It's a bird! It's a plane! It's Superman!";
// returns 38
alert(str.lastIndexOf("a"));
</script>Both these functions return the position of
the substring in the original string, or -1 if no match is found.
Of course, the indexOf() method only returns the first match - but what if you need to find the second or third match? Simply add an argument to the method call, indicating where in the string the indexOf() method should begin searching:
<script language="JavaScript">
// set string
var str = "It's a bird! It's a plane! It's Superman!";
// returns 18
alert(str.indexOf("a", 10));
</script>You can use the charAt() method to obtain the
character at a particular index position within the string.
<script language="JavaScript">
// set string
var str = "Batman and Robin";
// returns "t"
alert(str.charAt(2));
</script>
A common application of the charAt() method is
to iterate through a string, checking each character for validity against a pre-defined list. Consider the following example, which demonstrates how this works in the context of a password validator:
<html>
<head>
<script language="JavaScript">
// verify password string against allowed list of characters function
checkPassword() {
// error flag
var error = 0;
// list of valid characters
var validChars = "abcdefghijklmnopqrstuvwxyz1234567890";
// get value from form
var password = document.forms[0].password.value;
// iterate through string and check against allowed character
list
for (x=0; x<password.length; x++)
{
c = password.charAt(x);
if (validChars.indexOf(c) == -1)
{
error = 1;
break;
}
}
// display appropriate message
if (error == 1)
{
alert ("Error!");
return false;
}
else
{
alert ("All OK!");
return true;
}
}
</script>
</head>
<body>
<form>
Enter password: <input name="password" type="text">
<br>
<input type="submit" value="Check!" onClick="checkPassword()"> </form>
</body>
</html>Next: Search And Destroy >>
More JavaScript Articles
More By Harish Kamath, (c) Melonfire