簡體   English   中英

如何使用原始javascript正確突出顯示單詞?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM