您好我试图在每次字符串中找到特定字符的索引,并提供检测它的次数。
我想到的一种方法基本上是使用(str.replace(/[^char]/g, "").length)
查找字符串中的次数然后使用str.lastIndexOf("char")
并在从该索引向前删除字符后创建新字符串再检查一下,直到我找不到。
但我不认为这是最有效的方式,所以如果你有更好的方法,请告诉我?
让我们说:var str = "123456789017899199999100001"
我们需要每个1的索引以及在字符串中找到它的次数。
答案 0 :(得分:0)
您可以为值及其索引获取哈希表。然后将数组的长度作为计数。
var string = "123456789017899199999100001",
positions = Object.create(null);
[...string].forEach((v, i) => (positions[v] = positions[v] || []).push(i));
console.log(positions[1]);
console.log(positions[1].length);
console.log(positions);
.as-console-wrapper { max-height: 100% !important; top: 0; }
任何字符串的解决方案。
var string = "123456789017899199999100001",
positions = [],
index = -1,
search = "99";
while ((index = string.indexOf(search, index + search.length)) !== -1) {
positions.push(index);
}
console.log(positions);
console.log(positions.length);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
使用regexp进行此类任务是过度的,你是对的,它可以通过线性遍历字符串更简单的方式完成:
function count(str, char) {
var rval = {indices:[], count:0};
for(var i=0; i<str.length; i++) {
if (str[i] === char) {
rval.indices.push(i);
rval.count++;
}
}
return rval;
}
然后为你的字符串产生:
count(str,'1') // {indices:[0,10,15,21,26],count:5}
你也可以简单地返回索引数组,其长度是总出现次数