2017-04-11 47 views
0

我正在嘗試使用正則表達式構造函數找到字符串字符(變量)出現的次數,但它不起作用。正則表達式構造函數不能用於匹配字符串中的變量字

function getNumberOfOccurrences() 
{ 
    //get input from user: 
    var inputWord = document.getElementById("wordInputField").value; 
    inputWord = inputWord+""; // turn it into a string 
    var inputLetter = document.getElementById("letterInputField").value; 
    inputLetter = inputLetter+""; // turn it into a string 

    if(checkInput(inputWord , inputLetter)) // other function that checks the input 
    { 
     var rgxInputLetter = new RegExp(inputLetter, "g"); //use regex constructor for the match function: 

     var resultArray = inputWord.match(rgxInputLetter); // use match to find occurrences. match returns an array 

     var occurences = resultArray.length; // length of array should be the occurrences 

     if(isNaN(occurences) && occurences >= 0) // check that match function worked and an array was returned 
     { 
      document.getElementById("resultField").innerHTML = "There are "+occurences + " occurrences of: \""+inputLetter+"\" in the word: \""+inputWord+"\""; 
     } 
     else 
     { 
      document.getElementById("resultField").innerHTML = "There are no occurrences of: \""+inputLetter+"\" in the word: \""+inputWord+"\""; 
     } 



    } 


}  

它總是給我一個錯誤resultArray
即使我寫了inputLetter =「a」inputWord =「something」就在匹配函數之前。
爲什麼它不起作用?

+0

您是否嘗試過這樣的:http://regexr.com/? –

+1

「東西」裏有多少'a'? – Thomas

+0

謝謝你。這是一個很酷的網站。 – Davis8988

回答

0

發現它真的有效,問題是最後的條件isNaN(發生)
因爲它是檢查的條件是而不是一個數字。
應該添加了!標誌。 -_-
所以這個固定:
if(! isNaN(occurences) && occurences >= 0)

相關問題