Playing with Strings
<HTML>
<HEAD>
<TITLE>String Play</TITLE>
<SCRIPT>
function capWords(str){
var words = str.split(" ");
for (var i=0 ; i < words.length ; i++){
var aWord = words[i];
var firstLetter = aWord.substr(0,1);
var rest = aWord.substr(1, aWord.length -1)
words[i] = firstLetter.toUpperCase() + rest
}
document.theForm.results.value = words.join(" ");
}
function countWords(str){
var count = 0;
var words = str.split(" ");
for (i=0 ; i < words.length ; i++){
if (words[i] != "")
count += 1;
}
document.theForm.results.value = "(" + count + ")";
}
function revWords(str){
var words = str.split(" ");
var j = words.length - 1;
var backWords = new Array();
for (i=0 ; i < words.length ; i++){
backWords[j] = words[i];
j--;
}
document.theForm.results.value = backWords.join(" ");
}
function revString(str) {
var retStr = "";
for (i=str.length - 1 ; i > - 1 ; i--){
retStr += str.substr(i,1);
}
return retStr;
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="theForm">
<TABLE>
<tr><td colspan=5> Enter a text string: </td></tr>
<tr><td colspan=5><TEXTAREA name=inStr rows=5 cols=90></TEXTAREA>/td></tr>
<tr><td><INPUT type=button value="Capitalize Words" onClick="capWords(document.theForm.inStr.value)";>
</td><td><INPUT type=button value="Count Words" onClick="countWords(document.theForm.inStr.value)";>
</td><td><INPUT type=button value="Reverse Words" onClick="revWords(document.theForm.inStr.value)";>
</td><td><INPUT type=button value="Reverse String" onClick="document.theForm.results.value = revString(document.theForm.inStr.value)";>
</td><td>
<INPUT type=button value="Clear" onClick='document.theForm.inStr.value=""';>
</td></tr><tr><td colspan=5>
<br><hr> Results<br>
</td>
</tr>
<tr>
<td colspan=5>
<TEXTAREA name=results rows=5 cols=90>
</TEXTAREA>
</td>
</tr>
<tr>
<td colspan=5>
<INPUT type=button name="theButton" value="Clear Results"
onClick='document.theForm.results.value=""';>
</td>
</tr>
</TABLE>
</FORM>
</BODY>
</HTML>
Related examples in the same category