关键词高亮
检索关键词拆分
关键代码
text.split(keyword)
.flatMap(str => ([{text: keyword, class: 'highlight'}, {text: str}]))
.slice(1)
.filter(item => Boolean(item.text))
split
:按关键词拆分flatMap
:在每个分割后的的片段前增加一个高亮元素,补回切掉的关键词,但头部多一个高亮元素slice
:去掉头部多出的高亮元素
示例
const text = '1034056';
const keyword = '0';
text.split(keyword) // ['1', '34', '56'] 按关键词拆分
.flatMap(str => ([keyword, str])) // ['0', '1', '0', '34', '0', '56'] 往每项前面插入一项关键字
.slice(1).filter(Boolean) // ['1', '0', '34', '0', '56'] 去掉头部多出的项
const text = '01034056';
const keyword = '0';
text.split(keyword) // ['', '1', '34', '56'] 按关键词拆分
.flatMap(str => ([keyword, str])) // ['0', '', '0', '1', '0', '34', '0', '56'] 往每项前面插入一项关键字
.slice(1) // ['', '0', '1', '0', '34', '0', '56'] 去掉头部多出的项
.filter(Boolean) // ['0', '1', '0', '34', '0', '56'] 去掉空项
split
使用RegExp
来分割使结果中包含分割符
关键代码
text.split(new RegExp(`(${keyword})`))
.map(item => (item === keyword ? ({text: keyword, class: 'highlight'}) : ({text: item})));
示例
const text = '01034056';
const keyword = '0';
text.split(new RegExp(`(${keyword})`)) // ['', '0', '1', '0', '34', '0', '56']
.map(item => (item === keyword ? ({text: keyword, class: 'highlight'}) : ({text: item})));
// {text: ''},
// {text: '0', class: 'highlight'},
// {text: '1'},
// {text: '0', class: 'highlight'},
// {text: '34'},
// {text: '0', class: 'highlight'},
// {text: '56'}
示例代码
<input v-model="keyword" type="text">
<div>
<span v-for="(item, index) in list" ::key="index" :class="item.class">{{ item.text }}</span>
</div>
export default {
data() {
return {
text: `从每一个寻寻觅觅的日子里,穿行而过,看似捕手的,可能也是猎物,看似平常的,可能正是宝藏。灵魂触角,敏感或是迟钝,都有权尽情舞蹈,大千世界啊,风马牛秘密联络,肉眼所得,仅供参考。过去,当下,未来,未必真有界限,时间,只是行一个方便的幻觉。所以,无忧无惧,专心游戏,无牵无挂,寻宝之旅。广袤星河里亿万生命,何其有幸,与你一同在场,就在,这里。寻宝游戏演唱会。`,
keyword: ''
};
},
computed: {
list() {
const text = this.text;
const keyword = this.keyword;
if (!keyword) return [{ text }];
return text.split(new RegExp(`(${keyword})`)).filter(Boolean).map(item => (item === keyword ? ({text: keyword, class: 'highlight'}) : ({text: item})));
}
}
}
.highlight {
color: #f40;
}