例如,假设我的���符串包含:
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个字符。
我已经更新了这个答案。使用匹配的想法很好,但速度较慢:
console.log(("str1,str2,str3,str4".match(/,/g) || []).length); //logs 3
console.log(("str1,str2,str3,str4".match(new RegExp("str", "g")) || []).length); //logs 4
(mainStr.split(",").length - 1) //3
(mainStr.split("str").length - 1) //4
在@Lo的答案和我自己愚蠢的性能测试中,至少在Chrome中,split速度更快,但是创建额外的数组似乎并不明智。
至少有五种方法。最好的选项,也应该是最快的(由于本机RegEx引擎),置于顶部。
("this is foo bar".match(/o/g)||[]).length;
// returns 2
"this is foo bar".split("o").length - 1;
// returns 2
不建议使用Split,因为它会消耗大量资源。它为每个匹配分配新的'Array'实例。不要尝试在通过FileReader读取大于100MB文件时使用它。您可以使用Chrome 的分析器选项观察确切的资源使用情况。
var stringsearch = "o"
,str = "this is foo bar";
for(var count=-1,index=-2; index != -1; count++,index=str.indexOf(stringsearch,index+1) );
// returns 2
查找单个字符
var stringsearch = "o"
,str = "this is foo bar";
for(var i=count=0; i<str.length; count+=+(stringsearch===str[i++]));
// returns 2
元素映射和过滤。由于它需要预先分配资源而不是使用Python中的“生成器”,因此不推荐使用此方法:
var str = "this is foo bar"
str.split('').map( function(e,i){ if(e === 'o') return i;} )
.filter(Boolean)
//>[9, 10]
[9, 10].length
// returns 2
分享: 我制作了这个代码片段,目前包含8种字符计数方法,所以我们可以直接汇集和分享我们的想法 - 只是为了好玩,也许可以进行一些有趣的基准测试 :)
||[]
的作用,但这个答案很棒!对于其他还在迷惑的人来说,如果 match()
没有找到匹配项,则返回 null
,而 ||[]
会在 match()
返回 null
时返回长度为0的数组,这意味着 length()
将返回0而不是产生类型错误。 - NathanString.prototype.count=function(c) {
var result = 0, i = 0;
for(i;i<this.length;i++)if(this[i]==c)result++;
return result;
};
用法:
console.log("strings".count("s")); //2
"stringsstringstrings".count("str")
这个怎么处理? - Toskan简单地使用 split 函数来查找字符串中某个字符的出现次数。
mainStr.split(',').length
// 通过逗号作为分隔符进行拆分后的字符串数量为4
mainStr.split(',').length - 1
// 逗号的数量为3
更新:这个方案可能很简单,但并不是最快的。请参见下面的基准测试结果。
令人惊讶的是,在13年内,这个答案还没有出现过。直觉上,它似乎应该是最快的:
const s = "The quick brown fox jumps over the lazy dog.";
const oCount = s.length - s.replaceAll('o', '').length;
const s = "001101001";
const oneCount = s.replaceAll('0', '').length;
基准测试
const { performance } = require('node:perf_hooks');
const ITERATIONS = 10000000;
const TEST_STRING = "The quick brown fox jumps over the lazy dog.";
console.log(ITERATIONS, "iterations");
let sum = 0; // make sure compiler doesn't optimize code out
let start = performance.now();
for (let i = 0; i < ITERATIONS; ++i) {
sum += TEST_STRING.length - TEST_STRING.replaceAll('o', '').length;
}
let end = performance.now();
console.log(" replaceAll duration", end - start, `(sum ${sum})`);
sum = 0;
start = performance.now();
for (let i = 0; i < ITERATIONS; ++i) {
sum += TEST_STRING.split('o').length - 1
}
end = performance.now();
console.log(" split duration", end - start, `(sum ${sum})`);
10000 iterations
replaceAll duration 2.6167500019073486 (sum 40000)
split duration 2.0777920186519623 (sum 40000)
100000 iterations
replaceAll duration 17.563208997249603 (sum 400000)
split duration 8.087624996900558 (sum 400000)
1000000 iterations
replaceAll duration 128.71587499976158 (sum 4000000)
split duration 64.15841698646545 (sum 4000000)
10000000 iterations
replaceAll duration 1223.3415840268135 (sum 40000000)
split duration 629.1629169881344 (sum 40000000)
string.split('o').length - 1
。 - User_coder快速Google搜索得到以下结果(来自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
*
字符上的错误 (SyntaxError: nothing to repeat
)。 - user669677你还可以使用rest参数将字符串转换为元素数组,并使用以下方法操作:
const mainStr = 'str1,str2,str3,str4';
const commas = [...mainStr].filter(l => l === ',').length;
console.log(commas);
或
const mainStr = 'str1,str2,str3,str4';
const commas = [...mainStr].reduce((a, c) => c === ',' ? ++a : a, 0);
console.log(commas);
这里有一个类似的解决方案,但它使用了 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
要快得多。
_.countBy("abcda")['a'] //2
这种方法也适用于数组:
_.countBy(['ab', 'cd', 'ab'])['ab'] //2
undefined
而不是 0。 - Jay Wick好的,另一个正则表达式 - 可能不是很快,但比其他方法更简短易读,在我的情况下只需使用'_'
进行计数。
key.replace(/[^_]/g,'').length
只需去除所有不属于您字符的内容, 但如果输入为字符串,则看起来不太好看。