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」就在匹配函數之前。
爲什麼它不起作用?
您是否嘗試過這樣的:http://regexr.com/? –
「東西」裏有多少'a'? – Thomas
謝謝你。這是一個很酷的網站。 – Davis8988