2011-09-10 3 views
0
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 
    } 

私はここでアイデアがありません。私は解決する必要がある問題について説明します。何に対抗して何を印刷するのですか

> "matchAgainst"配列内の一致を検索します。ラインであった場合
> trueの場合、例えば

単語=量(昇順)を

返す「私はアヒルのふりをするたびにアヒルが私に笑顔はありません願っています!」、出力を次のようになります。

鴨= 2
笑顔= 1

(、それはunecesarryだ '=牛0' を表示しません)。しかしラインであった場合:「今日は、外出先ではなかったですod day "、出力なし。

ありがとうございます。

答えて

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

ここでは何が起こっていますか? http://jsfiddle.net/bE3yX/ アラートはありません ありがとうございます。 – DuckAreSuperior

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 />') 
} 
関連する問題