匹配并打印+金额

时间:2011-09-10 19:24:48

标签: javascript arrays match

var str = "I hope ducks don't smile upon me whenever I pretend to be a duck!";
var matchAgainst = ['duck', 'smile', 'cows']

for (var ma = 0; ma < matchAgainst.length; ba++)
    if (str = matchAgainst.match(matchAgainst))
    {
    document.write
    }

好吧,我在这里没有想法,我会解释我需要解决的问题。

&GT;在“matchAgainst”数组中搜索匹配。
&GT;如果为true,则返回

word =金额(升序)

例如,如果这条线是“我希望鸭子不会在我假装成鸭子的时候对我微笑!”,输出应为:

duck = 2
微笑= 1

(不要打'牛= 0',这是不可能的)

但如果这句话是:“今天不是好日子”,没有输出。

谢谢。

2 个答案:

答案 0 :(得分:0)

这将打印出来,而不是大多数排序。我马上就会工作:)

var string1 = "I hope ducks don't smile upon me whenever I pretend to be a duck!";

var matchAgainst = ['duck', 'smile', 'cows'];

for (var ma = 0; ma < matchAgainst.length; ma++)
{
    var regexp = new RegExp(matchAgainst[ma], 'g');
    var numMatches = string1.match(regexp).length;
    if (numMatches > 0)
        document.write(matchAgainst[ma] + ' = ' + numMatches + '<br />')
}

答案 1 :(得分:0)

请参阅下面的代码中的答案。你应该阅读javascript正则表达式对象。

var str = "I hope ducks don't smile upon me whenever I pretend to be a duck!";
var matchAgainst = ['duck', 'smile', 'cows']

//You need to make sure you use the same value for increment variable all the way through (was ba++)
for (var ma = 0; ma < matchAgainst.length; ma++) {
   //Make the search pattern a global regex so it will find all occurences
   var rg = new RegExp(matchAgainst[ma], "g");

   //Run the search, save results to mathces array
   var matches = str.match(rg);

   //If matches found, print the amount
   if(matches.length > 0) document.write(matchAgainst[ma] + ": " + matches.length + "<br>");
}