问题描述:

This question already has an answer here:

  • Count the number of occurences of a character in a string in Javascript

    16 answers

网友答案:

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;
相关阅读:
Top