Keyword search and highlighting in the website

I believe that friends should have experienced the search function of the website when browsing some websites. This function can not only quickly retrieve the content you care about, but also highlight the keywords you searched for. A SpringBoot project as an example to realize keyword search and highlighting in web pages

backend part

First look at the implementation of the backend. The core idea is to receive the parameters passed by the frontend, use fuzzy query in the SQL statement, and return the query result

I use Mybatis in the project, the following code is a fragment in the corresponding mapper file

<!--此处的key为用户搜索的内容-->
<select id="queryBlogByKey" resultType="Blog">
        select * from blog where (title like #{key} or content like #{key}) and deleted = 0
</select>

front end

The highlighting function is mainly implemented by the front end. The main content of the page is the search box and the content to be displayed. The main code is as follows:

<!--搜索框-->
<div>
  <form name="search" method="post" th:action="@{/blog/search}">
    <div class="ui fluid category search">
      <div class="ui icon input">
        <input class="prompt" type="text" name="key" id="key" placeholder="输入关键词...." th:value="${key}">
        <i onclick="document.forms['search'].submit()" class="circular search link icon"></i>
      </div>
    </div>
  </form>
</div>

<!--展示的内容-->
<div id="content">
  ...
</div>

Next is the code for highlighting keywords. The core idea is: get the content in the search box (that is, keywords), match all the keywords through regular expressions when rendering the displayed content, and render them all as span elements , and add style to change its color

function highlight() {
    
    
  var key = document.getElementById("key").value; // 获取搜索框中的内容
  if (key === "") {
    
     // 非空判断
    return;
  } else {
    
    
    var regExp = new RegExp(key, "g");
    var content = document.getElementById("content");
    // 替换关键词实现高亮
    content.innerHTML = content.innerHTML.replace(regExp, "<span style=\"color:red\">" + key + "</span>");
  }
}

The final effect is as follows:
insert image description here

Note: The highlighting function implemented here can only recognize the exact same content as the keyword, and cannot recognize uppercase and lowercase letters in English

Guess you like

Origin blog.csdn.net/wzc3614/article/details/127505498