我需要计算字符串中某个字符出现的次数。
例如,假设我的字符串包含:
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个字符。
当前回答
这是我的解决方案。很多解决方案已经张贴在我之前。但我喜欢在这里分享我的观点。
const mainStr = 'str1,str2,str3,str4';
const commaAndStringCounter = (str) => {
const commas = [...str].filter(letter => letter === ',').length;
const numOfStr = str.split(',').length;
return `Commas: ${commas}, String: ${numOfStr}`;
}
// Run the code
console.log(commaAndStringCounter(mainStr)); // Output: Commas: 3, String: 4
这是我的REPL
其他回答
var i = 0; var split_start = new Date().getTime(); while (i < 30000) { "1234,453,123,324".split(",").length -1; i++; } var split_end = new Date().getTime(); var split_time = split_end - split_start; i= 0; var reg_start = new Date().getTime(); while (i < 30000) { ("1234,453,123,324".match(/,/g) || []).length; i++; } var reg_end = new Date().getTime(); var reg_time = reg_end - reg_start; alert ('Split Execution time: ' + split_time + "\n" + 'RegExp Execution time: ' + reg_time + "\n");
我用ramda js的解决方案:
const testString = 'somestringtotest'
const countLetters = R.compose(
R.map(R.length),
R.groupBy(R.identity),
R.split('')
)
countLetters(testString)
链接到REPL。
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"))
快速搜索谷歌得到了这个(从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
我更新了这个答案。我更喜欢使用火柴的想法,但它更慢:
console.log((“str1,str2,str3,str4”.match(/,/g) ||[]).长度);日志 3 console.log((“str1,str2,str3,str4”.match(new RegExp(“str”, “g”)) ||[]).长度);日志 4
如果事先知道要搜索什么,可以使用正则表达式文字;如果不知道,可以使用RegExp构造函数,并传入g标志作为参数。
匹配结果为空,因此|| []
以下是我在2009年给出的原始答案。它创建了一个不必要的数组,但是使用分割更快(截至2014年9月)。我很矛盾,如果我真的需要速度,毫无疑问我会使用分拆,但我更喜欢使用匹配。
旧答案(2009年):
如果你在找逗号:
(mainStr.split(",").length - 1) //3
如果你在找str
(mainStr.split("str").length - 1) //4
在@Lo的回答和我自己的愚蠢的性能测试中,分裂在速度上领先,至少在Chrome中,但再次创建额外的数组似乎不理智。