【问题标题】:How to bold every matched letter when user typing a word?用户输入单词时如何将每个匹配的字母加粗?
【发布时间】:2020-10-29 00:36:36
【问题描述】:

这是我的 HTML 的一部分,足以看到问题,以及 JavaScript 代码,当用户的输入与我的标题或正文匹配时,我不知道如何将每个字母/单词加粗。当用户输入一些文本时,我正在使用 JSON API 持有者来获取 /posts。如果有人可以完成我的 boldSearchedWord() 函数,非常感谢!

HTML:

<div class="wrap-container">
 <div class="search-bar">
   <i class="fas fa-search"></i>
    <input type="text" placeholder="Please, start entering the text to search" class="search">
    <div class="items"></div>
 </div>
</div>

JavaScript:

// Ataching event listener
let myInput = document.querySelector('.search');
//setup before functions
let typingTimer;
let doneTypingInterval = 500;
let searchElement = document.querySelector('.items');
let sorryItemElement = '<div class="sorry-wrapper"><i class="fas fa-truck-loading"></i><a href="#" class="sorry-msg">Sorry, we couldn\'t find anything :(</a><div>';
let loadingItemElement = '<div class="loading"><i class="fas fa-spinner"></i> Loading...</div>';
// keyup event would be better, but it doesn't recognize backspace because backspace it's not printable key
myInput.addEventListener('keydown', () => {
    clearTimeout(typingTimer);
    if (myInput.value) {
        typingTimer = setTimeout(searchBodyTitle, doneTypingInterval);
    }
});


async function searchBodyTitle() {
    const query = myInput.value;
    // early return
    if (query === '') {
        clearItems();
        return;
    }

    try {
        startLoading();
        const result = await fetch(`https://jsonplaceholder.typicode.com/posts?q=${query}`);
        const data = await result.json();
        const posts = data.map(post => {
            return {
                title: post.title,
                body: post.body
            }
        });
        finishLoading();
        if (posts.length === 0) {
            searchElement.innerHTML += sorryItemElement;
        } else {
            posts.forEach(post => {
                let slicedTitle = post.title.slice(0, 30);
                let slicedBody = `${post.body.slice(0, 50)} ...`;
                newElement(slicedTitle, slicedBody);
            });
        }
        return data;
    } catch (error) {
        finishLoading();
        console.log(error);
    }
}

function clearItems() {
    searchElement.innerHTML = '';
}

function newElement(title, body) {
    let newElement = `<a href="#" class="item-options"><span class="dropdown-title">${title}</span><span class="dropdown-body">${body}</span></a>`;
    searchElement.innerHTML += newElement;
}

function startLoading() {
    clearItems();
    searchElement.innerHTML += loadingItemElement;
}

function finishLoading() {
    clearItems();
}

function boldSearchedWord() {
    let titles = document.querySelectorAll('.dropdown-title');
   
}

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    您可以使用下面的代码。

    它使用匹配值中的&lt;b&gt; 执行替换。 文末有demo。

    function escapeRegex(string) {
        return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    }
    
    function boldSearchedWord(text, search) {
      const escapedSearch = escapeRegex(search);
    
      // \\b: find just the words STARTING with the searched value 
      // g: find all words and not just the first one
      // m: find in multiple lines
      // i: ignore case sensitive
      const regexpExpression = new RegExp('\\b('+ escapedSearch + ')\\b', 'gmi');
      
      let additionalIndexValue = 0;
      let newText = text;
    
      while ((match = regexpExpression.exec(text)) !== null) {
        const boldMatch = '<b>'+ match[0] +'</b>';
        const matchStart = match.index + additionalIndexValue;
        const matchEnd = regexpExpression.lastIndex + additionalIndexValue;
        
        newText = newText.substr(0, matchStart) + boldMatch + newText.substr(matchEnd);
        
        // After each match, a '<b></b>' HTML element is added surround the searched string in the text
        // Then we need to add the additional value to the index for a correct replacement
        additionalIndexValue += 7; 
      }
      
      return newText;
    }
    

    学分:

    1. Is there a RegExp.escape function in JavaScript?
    2. Replace substring in string with range in JavaScript

    演示:https://jsfiddle.net/7rmfqxt0/

    【讨论】:

      猜你喜欢
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-07
      • 2020-02-19
      • 2018-08-30
      • 2016-05-02
      • 1970-01-01
      相关资源
      最近更新 更多