高亮显示关键词

2022/2/14 Javascript

一般搜索结果有时需要高亮搜索的词出来,这样用这种方法

<template>
  <div id="app">
    <h1>高亮关键词</h1>
    <input type="text" v-model="keyword" />
    <p class="text" v-html="highLightWord(text, keyword)"></p>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        keyword: '高亮',
        text: '如果你在输入框输入匹配到的词,就会高亮<br>If you enter the word matching in the input box, it will highlight',
      }
    },
    methods: {
      highLightWord(text, keyword) {
        if (!keyword) return text
        const regExp = new RegExp(keyword, 'gi')
        if (regExp.test(text)) {
          text = text.replace(regExp, '<mark>$&</mark>')
        }
        return text
      },
    },
  }
</script>

<style>
  #app {
    display: flex;
    flex-direction: column;
    color: #2c3e50;
    align-items: center;
    justify-content: center;
    height: 90vh;
    padding: 20px;
  }
  input {
    width: 100%;
    max-width: 500px;
    padding: 10px;
  }
  p {
    line-height: 2;
  }
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
最后更新: 2022/8/5 09:49:24