Categories:
Partners

String handling Examples

Before we go our separate ways, wouldn't you like to see a couple of examples on the utilization of these methods? Of course you would, and here they are!

-Loose Email Check Example

Let's start with a classic. This first example loosely checks the content of a form field to ensure it's a valid email address, by using indexOf() to check for the presence of the "@" and "." character:

Source Code:

<form name="test" onSubmit="checkemail(this.test2.value);return false">
<input type="text" size=20 name="test2"> <input type="submit" value="Submit">
</form>

<script type="text/javascript">
function checkemail(which){
if (which.indexOf("@")!=-1&&which.indexOf(".")!=-1)
alert("Good!")
else
alert("Quit fooling around and enter a valid email address!")
}
</script>

Note that I said "loose." "Simple" also is the script. All that's involved is indexOf() and the number "-1" (which indicates the searched characters are not present inside the form field).

-Word Count Example

Counting the number of words in any given text can be tedious a task...without the help of the split() method, that is. Here's an example using it (note the simplicity):

Source Code:

<form name="wordcount">
<textarea rows="12" name="wordcount2" cols="38" wrap="virtual"></textarea><br>
<input type="button" value="Calculate Words" onClick="countit()"> <input type="text" name="wordcount3" size="20">
</form>

<script type="text/javascript">
function countit(){
var formcontent=document.wordcount.wordcount2.value
formcontent=formcontent.split(" ")
document.wordcount.wordcount3.value=formcontent.length

}
</script>

Gotta love split() (and this tutorial!).

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.