我需要计算字符串中某个字符出现的次数。

例如,假设我的字符串包含:

var mainStr = "str1,str2,str3,str4";

我想求出逗号的个数,也就是3个字符。以及按逗号分隔后的单个字符串的计数,也就是4。

我还需要验证每个字符串,即str1或str2或str3或str4不应该超过,比如说,15个字符。


当前回答

我对接受的答案做了轻微的改进,它允许检查区分大小写/不区分大小写的匹配,并且是附加到字符串对象的方法:

String.prototype.count = function(lit, cis) {
    var m = this.toString().match(new RegExp(lit, ((cis) ? "gi" : "g")));
    return (m != null) ? m.length : 0;
}

Lit是要搜索的字符串(例如'ex'), cis是不区分大小写的,默认为false,它将允许选择不区分大小写的匹配。 要搜索字符串'I love StackOverflow.com'中的小写字母'o',你可以使用:

var amount_of_os = 'I love StackOverflow.com'.count('o');

Amount_of_os等于2。 如果我们再次使用不区分大小写的匹配来搜索相同的字符串,您将使用:

var amount_of_os = 'I love StackOverflow.com'.count('o', true);

这一次,amount_of_os将等于3,因为字符串中的大写O包含在搜索中。

其他回答

Leo Sauers回答中的第五种方法失败,如果字符位于字符串的开头。 如。

var needle ='A',
  haystack = 'AbcAbcAbc';

haystack.split('').map( function(e,i){ if(e === needle) return i;} )
  .filter(Boolean).length;

将给出2而不是3,因为过滤函数布尔为0给出false。

其他可能的过滤功能:

haystack.split('').map(function (e, i) {
  if (e === needle) return i;
}).filter(function (item) {
  return !isNaN(item);
}).length;

还有一个答案:

function count(string){
  const count={}
  
  string.split('').forEach(char=>{
    count[char] = count[char] ? (count[char]+1) : 1;
  })
  
  return count
}

console.log(count("abfsdfsddsfdfdsfdsfdsfda"))

你也可以休息你的字符串,并像使用元素数组一样使用它

Array.prototype.filter ()

const mainStr = 'str1,str2,str3,str4'; const逗号=[…mainStr]。Filter (l => l === ',').length; console.log(逗号);

Or

Array.prototype.reduce ()

const mainStr = 'str1,str2,str3,str4'; const逗号=[…mainStr]。Reduce ((a, c) => c === ',' ?++a: a, 0); console.log(逗号);

快速搜索谷歌得到了这个(从http://www.codecodex.com/wiki/index.php?title=Count_the_number_of_occurrences_of_a_specific_character_in_a_string#JavaScript)

String.prototype.count=function(s1) { 
    return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}

像这样使用它:

test = 'one,two,three,four'
commas = test.count(',') // returns 3

我正在做一个需要子字符串计数器的小项目。搜索错误的短语没有提供给我任何结果,然而在编写我自己的实现后,我偶然发现了这个问题。不管怎样,这是我的方法,它可能比这里的大多数慢,但可能对某些人有帮助:

function count_letters() {
var counter = 0;

for (var i = 0; i < input.length; i++) {
    var index_of_sub = input.indexOf(input_letter, i);

    if (index_of_sub > -1) {
        counter++;
        i = index_of_sub;
    }
}

http://jsfiddle.net/5ZzHt/1/

请让我知道,如果你发现这个实现失败或不遵循一些标准!:)

更新 你可能想要替换:

    for (var i = 0; i < input.length; i++) {

:

for (var i = 0, input_length = input.length; i < input_length; i++) {

上面讨论的内容很有趣: http://www.erichynds.com/blog/javascript-length-property-is-a-stored-value

我的解决方案:

function countOcurrences(str, value){
   var regExp = new RegExp(value, "gi");
   return str.match(regExp) ? str.match(regExp).length : 0;  
}