从字符串中提取单个值并计数

时间:2015-01-26 21:11:00

标签: javascript

我想在输入字段中输入文字,单击提交并仅排序元音。然后我想在输入字段下面显示元音的数量。

到目前为止,我已设法将用户键入字段的内容作为子字符串打印以分隔字母。我希望有人可以从这里向我提出一些方向/建议。

谢谢!



function myReverse() {
   var hello = document.getElementById("countVowels").value;
   var inputAnswer = hello.substring(-3);
   document.getElementById("numVowels").innerHTML = inputAnswer;
}

<form id="myVowels">
<input type="text" id="countVowels"  name="countVowels" />
</form>
<button onclick="myReverse()">Vowel counter</button>
<p id="numVowels"></p>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

根据您定义元音的方式,您应该可以使用正则表达式轻松完成。删除除元音之外的所有内容并检查字符串的长度。如果您想要唯一的计数或每个元音的计数,也可以这样做。

&#13;
&#13;
function myReverse() {
  var input = document.getElementById("countVowels").value;

  var lower = input.toLowerCase();
  var vowels = lower.replace(/[^aeiou]/g, "");

  document.getElementById("numVowels").textContent = "Input has " + vowels.length + " vowels.";

  // Count appearances of each vowel
  var vowelCounts = {};
  for (var i = 0; i < vowels.length; ++i) {
    var current = vowels[i];
    vowelCounts[current] = (vowelCounts[current] || 0) + 1;
  }

  document.getElementById("vowelCounts").textContent = JSON.stringify(vowelCounts);

  // Show unique counts
  // If you have a modern browser, you can use Object.keys(vowelCounts), otherwise:
  var counter = 0;
  for (var f in vowelCounts) {
    if (vowelCounts.hasOwnProperty(f)) {
      ++counter;
    }
  }

  document.getElementById("uniqueVowels").textContent = "Input has " + counter + " unique vowels.";
}
&#13;
<form id="myVowels">
  <input type="text" id="countVowels" name="countVowels" />
</form>
<button onclick="myReverse()">Vowel counter</button>
<p id="numVowels"></p>
<pre id="vowelCounts"></pre>
<p id="uniqueVowels"></p>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我认为这是你正在寻找的(如果我理解你的问题):

function myReverse() {
        var hello = document.getElementById("countVowels").value,
            vowels = ['a','e','i','o','u'],
            inputAnswer = [];

        for(var i = 0; i<vowels.length; i++) {
            if(hello.split(vowels[i]).length > 1) {
                inputAnswer.push(vowels[i]+': '+hello.split(vowels[i]).length);
            }
        }
        document.getElementById("numVowels").innerHTML = inputAnswer.join(', ');
    }

这是小提琴:

http://jsfiddle.net/y1usvehg/