[英]how to correctly highlight words using original javascript?
我正在尝试使用其他人的代码突出显示搜索文本中的所有单词
JavaScript代码在这里:
var s = document.querySelector('input[type="search"]'),
p = document.querySelector('p'),
find = function(){
var words = p.innerText.split(' '),
i = words.length,
word = '';
while(--i) {
word = words[i];
if(word.toLowerCase() == s.value.toLowerCase()){
words[i] = '<span class="highlight">' + word + "</span>";
}
else{
}
}
p.innerHTML = words.join(' ');
}
s.addEventListener('keydown', find , false);
s.addEventListener('keyup', find , false);
但是,在此代码中,如果要搜索一些以“。”结尾的单词,则不会为我提供正确的内容。 我发现,这是由var words = p.innerText.split(' ')
引起的,但是如果我使用split(/\\b(\\w+)\\b/g)
,则会引起额外的空间。 如何使用原始js使用正确的正则表达式来完成此任务?
您将无法一次性完成操作,您需要做的是首先像上面一样使用空白空间拆分p.innerHTML
,然后利用另一个功能来区分单词和标点符号。 我编写了一个函数,您可能会发现它对解决您的问题很有用。 运行代码以查看示例输出。
// This function will return the HTML for highlighting the word if successful // Othewise, it will return undefined function highlightWord(originalWord, newWord) { let re = /[.,:;]+$/ if (originalWord === newWord) { return `<span class="highlight">${newWord}</span>` } else if (re.test(newWord)) { let contains = new RegExp(`^${originalWord}`); let nonContainingPart = new RegExp(`[^${originalWord}]+`) if (contains.test(newWord)) { let word = newWord.match(contains) let punctuation = newWord.match(nonContainingPart) // Sample output of 'word' and 'punctuation' //word = [ 'book', index: 0, input: 'book...' ] //punctuation = [ '...', index: 4, input: 'book...' ] return `<span class="highlight">${word}</span>${punctuation}` } } } console.log(highlightWord('book', 'book')) console.log(highlightWord('book', 'book.')) console.log(highlightWord('book', 'book...')) console.log(highlightWord('book', 'book:')) console.log(highlightWord('book', 'book;')) console.log(highlightWord('booker', 'book;')) console.log(highlightWord('books', 'book;')) console.log(highlightWord('book', 'booka')) console.log(highlightWord('book', 'book-')) console.log(highlightWord('book', 'book_')) console.log(highlightWord('book', 'book~'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.