我有一个数组:
var locations = ['Afghanistan','Albania','Algeria','New York'];
和一个字符串:
var string = 'I love Afghanistan New York Afghanistan Andorra Andorra Algeria New York';
我想计算数组中每个关键字出现在字符串中的次数,但无法找出最佳方法。
答案 0 :(得分:5)
这是我的版本:
function countItems(a, s) {
var x, i, output = {};
for (x = 0; x < a.length; x++) {
i = 0;
output[a[x]] = 0;
while ((i = s.indexOf(a[x], i)) > -1) {
output[a[x]]++;
i++
}
}
return output;
}
var result = countItems(locations, string);
// result['Albania'] === 0
尝试here。
答案 1 :(得分:4)
尝试这样的事情。您可以使用count
修改您的操作 - 将其存储在另一个数组中,显示它(这是该脚本的作用)等。
var locations = ['Afghanistan','Albania','Algeria','New York'];
var str = 'I love Afghanistan New York Afghanistan Andorra Andorra Algeria New York';
for(var i=0; i<locations.length; i++) {
var pattern = new RegExp(locations[i], "g");
var m = str.match(pattern);
if (m != null)
{
var count = m.length; // the count
alert("There are " + count + " occurrences of " + locations[i]);
}
}
答案 2 :(得分:1)
<script language="JavaScript">
var locations = ['Afghanistan','Albania','Algeria','New York'];
var string1 = 'I love Afghanistan New York Afghanistan Andorra Andorra Algeria New York';
for (var i=0;i<locations.length;i++) {
nCount = string1.split(locations[i]).length-1;
document.write(locations[i] + ' is found ' + nCount + ' times<br>');
}
</script>
答案 3 :(得分:1)
此代码仅实例化一个 RegExp
对象并使用反向while循环。我很确定这是在不违反物理定律的情况下尽可能快地完成:)
这是最新发生的事情:
match()
match()
函数以下是实施:
var countries = ["Afganistan", "America", "Island"];
var sentence = "I love Afganistan, America.. And I love America some more";
function countOccurrences(a, s)
{
var re = "",
l = a.length,
m;
while (l)
{
l--;
re += a[l];
if (l > 0) re += "|";
}
m = s.match(new RegExp(re, "gi")) || [];
return m.length;
}
注意:我当然希望对任何会破坏函数内构造的正则表达式的特殊字符清理数组中的条目。
var occurrences = function countOccurrences(countries, sentence); // returns 3