1. 思路分析
如何将字符串中的指定字符在网页中高亮展示?
"Hello World";
将需要高亮的字符包裹 HTML 标签,为其单独设置颜色。
"Hello <span style="color: red">World</span>"
在 Vue 中如何渲染带有 HTML 标签的字符串?
<div>{{ htmlStr }}</div>
<div v-html="htmlStr"></div>
data () {
return {
htmlStr: 'Hello <span style="color: red">World</span>'
}
}
如何把字符串中指定字符统一替换为高亮(包裹了 HTML)的字符?
实现:将Hello World中的将Hello
高亮显示
const str = "Hello World"
"Hello World".replace('Hello', '<span style="color: red">Hello</span>')
// 结果 <span style="color: red">Hello</span> World
// 需要注意的是,replace 方法的字符串匹配只能替换第1个满足的字符
// 如果想要全文替换,使用正则表达式
// g 全局
// i 忽略大小写
"Hello World Hello abc".replace(/Hello/gi, '<span style="color: red">Hello</span>')
// <span style="color: red">Hello</span> World <span style="color: red">Hello</span> abc
结合字符串的 split
与数组的 join
var str = "hello world 你好 hello";
// ["", " world 你好 ", ""]
const arr = str.split("hello");
// "<span>hello</span> world 你好 <span>hello</span>"
arr.join("<span>hello</span>");
具体实现
1. 在列表项中绑定调用
<template>
<div class="search-suggestion">
// 输入框
<input type="text" v-model="searchText" />
// 建议列表
<van-cell :key="index" v-for="(item, index) in suggestions" icon="search">
* // v-html中绑定调用
<div slot="title" v-html="highlight(item)"></div>
</van-cell>
</div>
</template>
export default {
data() {
return {
suggestions: [], // 联想词数组
searchText: null// 输入框绑定的值
}
},
}
2. 在 methods 中添加一个方法处理高亮
highlight(text) {
const highlightStr = `<span class="active">${this.searchText}</span>`;
// 正则表达式 中间的内容都会当作匹配字符来使用,而不是数据变量
// RegExp 正则表达式构造函数
// 参数1:匹配模式字符串,它会根据这个字符串创建正则对象
// 参数2:匹配模式,要写到字符串中
const reg = new RegExp(this.searchText, 'gi');
// text.replace(/匹配的内容/gi, highlightStr)
return text.replace(reg, highlightStr);
}