Count the vowels of an input?

后端 未结 6 1969
小鲜肉
小鲜肉 2021-01-27 10:25

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


         


        
6条回答
  •  情歌与酒
    2021-01-27 10:58

    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;    
    Phrase:

提交回复
热议问题