How to count the characters in a input text [closed]

As this is a school project and you tagged jQuery, I am going to give you a jQuery solution sans explaination.

$(function() {
  function countChar(n, h) {
    // Input: Needle, Haystack (Case Sensative)
    // Output: number of needles
    var re = new RegExp(n, 'g'),
      matches = h.matchAll(re),
      r = 0;
    for (var m of matches) {
      r++;
      console.log("Found '" + m[0] + "' start=" + m.index + " end=" + (m.index + m[0].length) + ".");
    }
    return r;
  }
  $("#phrase").keyup(function() {
    var q = $("#query").val(),
      t = $(this).val(),
      c = countChar(q, t);
    $("#results").html("Found " + c + " of '" + q + "' (" + Math.round((c / t.length) * 100) + "%)");
  });
  $("#query").change(function() {
    var q = $("#query").val(),
      t = $("#phrase").val(),
      c = countChar(q, t);
    $("#results").html("Found " + c + " of '" + q + "' (" + Math.round((c / t.length) * 100) + "%)");
  });

  $("#phrase").val("The quick brown fox jumps over the lazy dog").trigger("keyup");
})
#results {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <label>Phrase</label> <input type="text" id="phrase" />
  <label>Find</label> <input type="text" id="query" value="a" />
  <span id="results"></span>
</div>

References

Leave a Comment