简体   繁体   中英

how to correctly highlight words using original javascript?

I am trying to highlight all words from search text using other people's code

The JavaScript code is here:

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);

However, in this code if want to search some words end with '.', it won't give me correct content. I figure out, it is caused by var words = p.innerText.split(' ') however if I used split(/\\b(\\w+)\\b/g) it will cause the extra space. How can I use right regular expression to accomplish this using original js?

You won't be able to do it in one shot, what you would need to do is first split p.innerHTML using an empty space as you've already done above, but utilize another function to differentiate between the word and the punctuation. I've written a function that you may find useful to solve your problem. Run the code to see sample outputs.

 // 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~')) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM