JavaScript Tutorial/String/Words — различия между версиями

Материал из Web эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 08:24, 26 мая 2010

Capitalize the words

<HTML>
<HEAD>
<SCRIPT>
function capWords(str){
   words = str.split(" "); 
   for (i=0 ; i < words.length ; i++){
      testwd = words[i];
      firLet = testwd.substr(0,1); //lop off first letter
      rest = testwd.substr(1, testwd.length -1)
      words[i] = firLet.toUpperCase() + rest   
   }         
   document.theForm.results.value = words.join(" ");
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="theForm">
Enter a text string:
<TEXTAREA name=inStr rows=5 cols=90>
</TEXTAREA>
<INPUT type=button value="Capitalize Words" onClick="capWords(document.theForm.inStr.value)";>
<INPUT type=button name="theButton" value="Clear Results" onClick="document.theForm.results.value=""";>
Results<br>
<TEXTAREA name=results rows=5 cols=90>
</TEXTAREA>
</FORM>  
</BODY>
</HTML>


Count the words

<HTML>
<HEAD>
<SCRIPT>
function countWords(str){
   var count = 0;
   words = str.split(" "); 
    for (i=0 ; i < words.length ; i++){
       // inner loop -- do the count
       if (words[i] != "")
          count += 1; 
    }
   document.theForm.results.value = 
      "There are " +
      count +
      " words in the text string you entered!";
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="theForm">
Enter a text string:
<TEXTAREA name=inStr rows=5 cols=90>
</TEXTAREA>
<INPUT type=button value="Count Words" onClick="countWords(document.theForm.inStr.value)";>
<INPUT type=button name="theButton" value="Clear Results" onClick="document.theForm.results.value=""";>
Results<br>
<TEXTAREA name=results rows=5 cols=90>
</TEXTAREA>
</FORM>  
</BODY>
</HTML>


Reverse the words

<HTML>
<HEAD>
<SCRIPT>
function revWords(str){
   words = str.split(" ");
   j = words.length - 1;
   backWords = new Array(); 
   for (i=0 ; i < words.length ; i++){
      backWords[j] = words[i];
      j--
   }         
   document.theForm.results.value = backWords.join(" ");
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="theForm">
Enter a text string:
<TEXTAREA name=inStr rows=5 cols=90>
</TEXTAREA>
<INPUT type=button value="Reverse Words" onClick="revWords(document.theForm.inStr.value)";>
<INPUT type=button name="theButton" value="Clear Results" onClick="document.theForm.results.value=""";>
Results<br>
<TEXTAREA name=results rows=5 cols=90>
</TEXTAREA>
</FORM>  
</BODY>
</HTML>