且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计数输入的元音?

更新时间:2023-09-18 22:19:16

另一个选择到其他的答案是使用常规的前pression。这不一定是更容易理解,或特别有效,但我给它作为替代。 (这也继续证明谚语:给予100程序员来解决一个问题,你会得到100解决方案)

在JavaScript中使用会匹配所有元音下面前pression,您可以使用返回数组,看看有多少...

  / [AEIOU] / IG

I 使得它不区分大小写,以及先按g 意味着全球因此将多次回暖。

下面是它在行动...

\r
\r
 函数誓言(形式){\r
  VAR一个= form.CountVowels.value;\r
  VAR匹配= a.match(/ [AEIOU] / IG);\r
  VAR标志= 0;\r
  如果(匹配!= NULL)\r
    标志= matches.length;\r
  警报(标志);\r
}\r
\r
功能的init(){\r
  VAR按钮1 =的document.getElementById(BTN1)\r
  button1.onclick =功能(){誓言(的document.getElementById(MyForm的)); }\r
}\r
\r
在window.onload = init;方法

\r

 <表ID =MyForm的行动=demo_form.asp>\r
  一句话:<输入类型=文本ID =输入1NAME =CountVowelsVALUE =将词语在这里>< BR>\r
  <输入类型=按钮ID =BTN1VALUE =检查元音>\r
< /形式为GT;

\r

\r
\r

Hi I am trying to count the vowels of the input of the form in my HTML using javascript currently with no success.

Here is my HTML

<!doctype html>
<html>
<head>
    <script src='p3-vowels.js'></script>
</head>
<body>
    <form action="demo_form.asp">
    Phrase: <input type="text" id = "input1" name="CountVowels" value="Put   Phrase Here"><br>
    <input type="button" id = "btn1" value="Check for Vowels">
    </form>
</body>
</html>

and here is my javascript

function vow(form){
    var a = form.CountVowels.value;
        flag = 0;

    for (var i = 0; i < a.length; i++){
        switch (a[i]){
            case 'a'
            case 'e'
            case 'i'
            case 'o'
            case 'u'
                flag++;
                break;
        }
    }
    alert(flag);
}

function init(){
    var button1 = document.getElementById("btn1")
    button1.onclick = vow;
}

window.onload = init;

Another option to the other answers is to use a regular expression. This is not necessarily easier to understand, or particularly efficient, but I'm giving it as an alternative. (It also continues to prove the proverb: give a 100 programmers a problem to solve and you'll get 100 solutions)

The following expression used in javascript will match all the vowels, and you can use the returning array to see how many there are...

/[aeiou]/ig

The i makes it case insensitive, and the g means global so it will pick up multiple times.

Here is it in action...

function vow(form){
  var a = form.CountVowels.value;
  var matches = a.match(/[aeiou]/ig);
  var flag = 0;
  if (matches != null)
    flag = matches.length;
  alert(flag);
}

function init(){
  var button1 = document.getElementById("btn1")
  button1.onclick = function() { vow(document.getElementById("myform")); }
}

window.onload = init;    

<form id="myform" action="demo_form.asp">
  Phrase: <input type="text" id = "input1" name="CountVowels" value="Put   Phrase Here"><br>
  <input type="button" id = "btn1" value="Check for Vowels">
</form>