var _myTxt;
var _myWord;
var _count;
var _count2;
function _findWord() {
_myTxt = document.getElementById('myTextBox').value;
_myWord = document.getElementById('myTxtField').value;
var re = new RegExp(_myWord, "gi");
_myTxt = _myTxt.replace(re, "<span style='font-weight: bold'>$&</span>");
_count = _myTxt.match(re);
_count2 = _count.length;
alert(_count.length); // alert returns nothing when there is 0 match ?!
if (_count < 1) {
document.getElementById("_idProcessedTxt").innerHTML = "There is no matching occurence for searched word";
} else {
document.getElementById("_idProcessedTxt").innerHTML = _myTxt;
document.getElementById("_idProcessedTxt2").innerHTML = ("Your word was matched : " + _count2 + " times.");
}
}
你好,上面的代码应该是:
- 用另一个字符串替换一个字符串(实际上与 span 标签相同的字符串)和
- 计数出现/替换的次数。
它适用于至少有一个或多个匹配项的所有情况。出于某种原因,我不明白,当输入的单词根本不返回匹配项时,它就不起作用了。这似乎完全破坏了代码,即使当匹配为 0 时警报也不返回任何内容。
任何线索为什么?