-2

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?

gespinha
  • 7,968
  • 16
  • 57
  • 91

5 Answers5

5

Though i would call it a hack but can work

var count = text.split("e").length - 1;
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
5

You can use a regex as follows:

var matches = text.match(/e/g);
var cnt = matches && matches.length || 0;
skypjack
  • 49,335
  • 19
  • 95
  • 187
2

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.

kemiller2002
  • 113,795
  • 27
  • 197
  • 251
1

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;
}

secretgenes
  • 1,291
  • 1
  • 19
  • 39
0

You can use regex for this:

var string = "on nsjcvndfpwnv";
var match = string.match(/e/g);
var count = match ? match.length : 0;
Tyr
  • 2,810
  • 1
  • 12
  • 21