我需要计算字符串中某个字符出现的次数。
例如,假设我的字符串包含:
var mainStr = "str1,str2,str3,str4";
我想求出逗号的个数,也就是3个字符。以及按逗号分隔后的单个字符串的计数,也就是4。
我还需要验证每个字符串,即str1或str2或str3或str4不应该超过,比如说,15个字符。
我需要计算字符串中某个字符出现的次数。
例如,假设我的字符串包含:
var mainStr = "str1,str2,str3,str4";
我想求出逗号的个数,也就是3个字符。以及按逗号分隔后的单个字符串的计数,也就是4。
我还需要验证每个字符串,即str1或str2或str3或str4不应该超过,比如说,15个字符。
当前回答
下面是一个类似的解决方案,但它使用了Array.prototype.reduce
function countCharacters(char, string) {
return string.split('').reduce((acc, ch) => ch === char ? acc + 1: acc, 0)
}
如前所述,String.prototype.split的工作速度比String.prototype.replace快得多。
其他回答
下面是最简单的逻辑,很容易理解
//Demo string with repeat char
let str = "Coffee"
//Splitted the str into an char array for looping
let strArr = str.split("")
//This below is the final object which holds the result
let obj = {};
//This loop will count char (You can also use traditional one for loop)
strArr.forEach((value,index)=>{
//If the char exists in the object it will simple increase its value
if(obj[value] != undefined)
{
obj[value] = parseInt(obj[value]) + 1;
}//else it will add the new one with initializing 1
else{
obj[value] =1;
}
});
console.log("Char with Count:",JSON.stringify(obj)); //Char with Count:{"C":1,"o":1,"f":2,"e":2}
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"))
var mainStr = “str1,str2,str3,str4”; var splitStr = mainStr.split(“,”).length - 1;减去 1 很重要! alert(splitStr);
分割成一个数组会给我们一些元素,这些元素总是比字符的实例数多1。这可能不是最有效的内存,但如果您的输入总是很小,这是一种直接且易于理解的方法。
如果您需要解析非常大的字符串(大于几百个字符),或者如果这是在处理大量数据的核心循环中,我会推荐不同的策略。
简单地说,使用分割来找出字符串中某个字符出现的次数。
mainStr.split(" ")。Length //给出4,这是使用分隔符逗号分隔后的字符串数 mainStr.split(" ")。Length - 1 //给出3,这是逗号的计数
我发现在非常大的字符串(例如,长度为1 000 000个字符)中搜索字符的最佳方法是使用replace()方法。
window.count_replace = function (str, schar) {
return str.length - str.replace(RegExp(schar), '').length;
};
您还可以看到另一个JSPerf套件用于测试该方法以及在字符串中查找字符的其他方法。