I have the following string variable:
var text = "one ensjcvndfpwenv";
How can I find, through pure Javascript how many e
characters are there in the string?
I have the following string variable:
var text = "one ensjcvndfpwenv";
How can I find, through pure Javascript how many e
characters are there in the string?
Though i would call it a hack but can work
var count = text.split("e").length - 1;
You can use a regex as follows:
var matches = text.match(/e/g);
var cnt = matches && matches.length || 0;
Outside of the split method, there is no real easy way to ultimately do it without counting up the instances in pure JavaScript (no regex involved).
function findNumberOfCertainCharacters(character, searchString){
var searchStringLength = searchString.length, counter = 0;
for(var ii = 0 ; ii < searchStringLength; ii++){
if(searchString[ii] === character){counter ++;}
}
return counter;
}
Personally, I think the other methods are better, but this is the pure JavaScript way of doing it without creating a new string array.
You can use the indexOf() method to count the occurrence
var pos = 0;
var occ = -1;
var i = -1;
var text = "one ensjcvndfpwenv";
while (pos != -1)
{
pos = graf.indexOf("e", i + 1);
occ += 1;
i = pos;
}
You can use regex for this:
var string = "on nsjcvndfpwnv";
var match = string.match(/e/g);
var count = match ? match.length : 0;