开发者

Match against and print what + amount

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
    }

Well, I'm out of ideas here si I'll explain what problem I need to be solved.

> Search for a match i开发者_如何学运维n "matchAgainst" array.

> If true, return

word = amount(ascending order)

For example if the line was "I hope ducks don't smile upon me whenever I pretend to be a duck!", the output should be:

duck = 2

smile = 1

(Don't print 'cow = 0', it's unecesarry)

But if the line was: "Today was not a good day", no output.

Thank you.


See answers in code below. You should read up on the javascript regular expression object.

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>");
}


This will print it out without sorting it by most. I'll have that working in a moment :)

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 />')
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜