正则表达式构造函数不适用于匹配字符串字

时间:2017-04-11 23:10:03

标签: javascript regex string-matching

我试图使用正则表达式构造函数查找字符串中字符串字母(变量)的出现次数,但它不起作用。

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 null
即使我在匹配功能之前写了 inputLetter =“a” inputWord =“something”
为什么不起作用?

1 个答案:

答案 0 :(得分:0)

发现它确实有效,问题是最后一条条件 isNaN(出现)
检查发生的情况是一个数字 应该加一个!标志。 -_-
所以这解决了它:
if( ! isNaN(occurences) && occurences >= 0)