Front-end Vue development, when searching with multiple keywords, the search results are highlighted (solve the problem of rendering html tags incorrectly when inputting English)

Problem background:

Internet search about the highlighting of search results is basically a single keyword search, or multi-keyword search, but it does not solve
the problem of rendering html tags when entering English characters. For example, when performing multi-keyword searches, it may It will perform a;s search,
and it is possible to parse the span tag and then highlight it, so that the highlight of html will appear when the data is rendered.

The error is shown in the figure:

insert image description here

Solutions

Because it is a multi-keyword search, the first thing to consider is to convert the keyword into a data, and perform a cyclic comparison between the keyword and the text information. If it is found to be
repeated, it will be highlighted. If the first keyword before The keywords have been displayed, then the html tag already exists in the text at this time
, at this time, convert the html tag into a special symbol, put the representative content of all these special symbols into an array, and then highlight and render the
html Labels, after completion, replace the original special symbols, and replace them with the html labels that need to be displayed in turn.

Solution

Through search induction, we can use the following method to solve the problem of highlighting multi-keyword search results.

<div id="content">
    aaaaassssaaassddddwwwssaaa
</div>

<script>
    function hightLight() {
      
      
        let textEle = document.getElementById('content');  //获取文本内容;
        var text = textEle.innerHTML
        let searchKeywords = 's;a;w';  //为了方便演示,这里关键词直接写死
        searchKeywords = searchKeywords.replace(/;|;/g, ',');
        let searchArray = [];
        searchArray = searchKeywords.split(',');//把关键词列为一个数组

        searchArray.forEach((keyword) => {
      
        //循环关键词数组
            if (keyword && text.indexOf(keyword) !== -1) {
      
      
                let regHtml = new RegExp("\<.*?\>", "ig"); //定义html正则
                let dealHtml = text.match(regHtml);  //符合的html定义一个数组
                let num = -1;
                text = text.replace(regHtml, '{~}'); //用一个特殊字符进行替换
                text = text.replace(new RegExp(keyword, 'g'), `<span style="color:#1890FF;">${ 
        keyword}</span>`);
                //把原来~代表的html标签,再替换回来
                text = text.replace(/{~}/g, function () {
      
      
                    num++;
                    return dealHtml[num];  //进行依次替换
                });
            }
        })

        textEle.innerHTML = text;

    }
    hightLight();
</script>

renderings

insert image description here
You can see that all English is highlighted, and no html is displayed.

Guess you like

Origin blog.csdn.net/m54584mnkj/article/details/129123650