2011-09-10 6 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

아래 코드의 답을 참조하십시오. 당신은 자바 스크립트 정규식 객체를 읽어야한다.

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