admin管理员组

文章数量:1419656

is it possible to get the number of SAME letters from a pararaph using jQuery? so let's say I have this paragraph:

<div>like this printer</div>

I would like to get the number of characters for "i" meaning that I should get 3 since there are 3 "i"s. I was thinking about using $(div:contains(i)), but now sure how to implement this. Any suggestions? Thanks a lot!

is it possible to get the number of SAME letters from a pararaph using jQuery? so let's say I have this paragraph:

<div>like this printer</div>

I would like to get the number of characters for "i" meaning that I should get 3 since there are 3 "i"s. I was thinking about using $(div:contains(i)), but now sure how to implement this. Any suggestions? Thanks a lot!

Share Improve this question edited Jan 13, 2016 at 8:25 HenryDev asked Jan 13, 2016 at 5:40 HenryDevHenryDev 5,0036 gold badges30 silver badges69 bronze badges
Add a ment  | 

7 Answers 7

Reset to default 5
//Your string
var str = "I like this printer";

//Shows the count of "i" in your string.
console.log(str.replace(/[^i]/g, "").length);

Happy Coding!

Try this demo:

var src = $('#src').text();

var count = (src.match(/i/g) || []).length;

$('#count').append(count);

alert(count);
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="src">like this printer</div>
<p id="count"><strong>Count of "i" = </strong></p>

use .text().split()

$('div').text().split('i').length - 1;

Firstly, you should understand :contains selector. Lastly, you can try this.

$("div:contains('i')").html().split('').reduce(function(p, n) {
   return n === 'i' ? ++p : p;
}, 0);

Almost all (all?) of the solutions proposed thus far will fail if the character being searched for is "special" to Regex's (for example, '.'). Here is a method which works regardless of the character being searched for (because it doesn't use a regex):

function countInstancesOf ( str, i ) {
    var count = 0;
    var pos = -1;

    while ((pos = str.indexOf(i, pos+1)) !== -1) ++count;
    return count;
}

var howmany = countInstancesOf( $('div').text(), 'i' );

Here is a method based on String.match() and Array.length:

function countSameCharsInElement(char,string){
    string.match(new RegExp(char, "g")) || []).length);
}

Sample usage:

countSameCharsInElement('i',$('div').text());

your answering own question. look up contains for strings in JavaScript. an easy to reference for a lot things web is w3 schools. look there you will find your answer I remend you do some more web searching before asking stack overflow.

本文标签: javascriptHow to get the NUMBER of same characters from a paragraph using jQueryStack Overflow