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

<script>
export default {
  data() {
    return {
      keyword: "word",
      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>
body {
  background: #f3f6fd;
}
#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;
  box-shadow: 0 0.5em 1em -0.125em rgb(10 10 10 / 10%),
    0 0px 0 1px rgb(10 10 10 / 2%);
  border: none;
  border-radius: 99px;
  text-align: center;
}
input:focus {
  outline: none;
}
p {
  line-height: 2;
}
</style>

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.