1、演示
2、说明
网上这类教程大多采用正则表达式进行文本替换,然而,这种方法有时无法完全匹配,或者会因为特殊符号而产生 Bug。本文将提供一种完美的解决方案,确保百分之百匹配文本。
3、函数封装
封装一个函数,进行通用,避免重复写这段代码
const textHighlighting = (textItem, searchText) => { const searchTextArr = searchText.split('') const textItemArr = textItem.split('') const result = textItemArr.map(item => { return searchTextArr.includes(item) ? `<span style="color:red;">${item}</span>` : item }) return result.join('') }
- 定义函数
textHighlighting
,接收两个参数textItem
和searchText,textItem
表示要处理的文本,searchText
表示要搜索并高亮的文本。- 将
searchText
和textItem
分别转换为字符数组searchTextArr
和textItemArr
。- 使用
map
方法遍历textItemArr
中的每个字符。- 对于每个字符,检查是否存在于
searchTextArr
中。- 如果存在,则用
<span style="color:red;">
包裹该字符,以实现红色高亮效果。- 否则保持原样。
- 使用
join
方法将处理后的字符数组组合成字符串。- 返回处理后的字符串作为函数的结果。
您可以参考以下两个案例,直接复制该函数到您的项目中即可使用。
4、在Vue中使用
<template> <div> <input type="text" v-model="searchText" /> <ul v-if="searchText"> <li v-for="item in data" :key="item.id" v-html="textHighlighting(item.text, searchText)"></li> </ul> </div> </template> <script setup> import { ref, reactive } from 'vue' const searchText = ref('') const textHighlighting = (textItem, searchText) => { const searchTextArr = searchText.split('') const textItemArr = textItem.split('') const result = textItemArr.map(item => { return searchTextArr.includes(item) ? `<span style="color:red;">${item}</span>` : item }) return result.join('') } const data = [ { id: 1, text: '文字高亮' }, { id: 2, text: '前端实现文字高亮' }, { id: 3, text: '前端怎么实现文字高亮' }, { id: 4, text: '实现文字高亮的办法' }, { id: 5, text: 'Vue实现文字高亮' }, { id: 6, text: '高亮文字怎么做' }, { id: 7, text: '在Vue中(文字高亮)怎么做' }, { id: 8, text: '文字实现高亮效果' }, ] </script> <style scoped lang="scss"></style>
5、在原生JS中使用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <input type="text" /> </body> <script> const data = [ { id: 1, text: '文字高亮' }, { id: 2, text: '前端实现文字高亮' }, { id: 3, text: '前端怎么实现文字高亮' }, { id: 4, text: '实现文字高亮的办法' }, { id: 5, text: 'Vue实现文字高亮' }, { id: 6, text: '高亮文字怎么做' }, { id: 7, text: '在Vue中(文字高亮)怎么做' }, { id: 8, text: '文字实现高亮效果' }, ] const ipt = document.querySelector('input') const textHighlighting = (textItem, searchText) => { const searchTextArr = searchText.split('') const textItemArr = textItem.split('') const result = textItemArr.map(item => { return searchTextArr.includes(item) ? `<span style="color:red;">${item}</span>` : item }) return result.join('') } ipt.addEventListener('input', function () { const ul = document.createElement('ul') document.body.removeChild(ul) if (this.value) { data.forEach(item => { const li = document.createElement('li') li.innerHTML = textHighlighting(item.text, this.value) ul.appendChild(li) }) document.body.appendChild(ul) } }) </script> </html>