0

Trying to practice jQuery on jsfiddle. I'm trying to count how many letters are in the div element. What am I doing wrong (I'm sure a LOT of things) and am I using the right methods?

Thanks in advance :)

edit: sorry, i wasn't trying to really how many letters in the string, but how many of the letter i'm want to query, is in the div element. i guess if i want to count the letters i would just use .length, but shouldn't I use a loop to go through the string and see if the letter I'm looking for is in the string?

HTML

<div>Hello!</div>

jQuery

$(document).ready(function() {
  var countLetters = function (letter) {
    var counter = 0;
    for (i = 0; i <= $('div').length; i++) {
      if ($('div')[i] == letter) {
        counter++;
        $('div').append('<p>There are ' + counter + ' ' + letter + 's</p>');
      } else {
        $('div').append('<p>That letter isn\'t found</p>');
      }
    }
  }
 countLetters('e');
});
4
  • 2
    Possible duplicate of Jquery count characters Commented Mar 7, 2016 at 6:52
  • $('div')[i] is a dom element reference... so that will never be equal to letter Commented Mar 7, 2016 at 6:52
  • You need to read the text contents of the div and count the letters Commented Mar 7, 2016 at 6:53
  • thanks for the input. can you provide insight on how i can achieve this? i shoud have used better wording on my title. I'm not trying to count how many letters are in the string, but see if the string contains the letters im searching for. Commented Mar 7, 2016 at 7:02

1 Answer 1

0

You can use regex to accomplish your check.

Please read the notes in the code.

$(document).ready(function() {
  var countLetters = function (letter) {
    // get the div's text
    var divText = $('div').text(),
        // create regex that contains the letter only and 'g' modifier to find the all instanses.
        regex = new RegExp(letter, 'g'),
        // divText.match return an array with all matches so you can get the .length
        counter = divText.match(regex).length;

    console.log(counter);

    // now it's a regular check
    if (counter > 0) {
      $('div').append('<p>There are ' + counter + ' ' + letter + 's</p>');
    } else {
      $('div').append('<p>That letter isn\'t found</p>');
    }

  }
  countLetters('e');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Heeello!</div>

http://jsbin.com/huqados/edit?html,js

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.