点击here获取我迄今为止尝试过的小提琴链接。
如果搜索输入字符串与文本区域中的字符串匹配,则应突出显示匹配的文本。匹配应基于单词。可以是部分匹配或完全匹配, 但匹配应从文本区域中每个单词的开头开始匹配。
请在小提琴中找到注释,需要修复的问题
// Core function
function buildRegexFor(find) {
var regexStr = find.substr(0,3);
for (var i = 0; i < find.length - 2; i++) {
regexStr = '(\\b' + regexStr + find.substr(i+2,1) + '?|' + find.substr(i,3) + ')';
}
return regexStr;
}
// Handle button click event
document.querySelector('button').onclick = function () {
// (1) read input
var find = document.querySelector('input').value;
var str = document.querySelector('textarea').value;
// (2) build regular expression using above function
var regexStr = buildRegexFor(find);
// (3) apply regular expression to text and highlight all found instances
str = str.replace(new RegExp(regexStr, 'g'), "<strong class='boldtxt'>$1</strong>");
// (4) output
document.querySelector('span').textContent = regexStr;
document.querySelector('div').innerHTML = str;
};
.boldtxt {
color: red;
}
p {
color: red
}
Value to find:
<br>
<input value="pota % rat on are ota">
<br>
<button>find</button>
<br> Text to find in:
<br>
<textarea cols=40>There is a spot in % the rat botanic garden on this atol that beats all stats as it rotates potatoes.</textarea>
<br> Regex: <span></span>
<br>
<div></div>
<p>Note: </br> 1> Last "t" in "potat" should not be highligted </br> 2> First "t" in "the" should not be highlighted</br> 3> "ota" in "botanic" and "rotates" should not be highlighted</p>