1. Analysis of ideas

How to place a specified character in a string inWeb pageMedium highlight?

"Hello World";
Copy the code

Wrap the HTML tag around the characters that need to be highlighted and color them separately.

"Hello <span style="color: red">World</span>"
Copy the code

How do I render strings with HTML tags in Vue?

<div>{{ htmlStr }}</div>
<div v-html="htmlStr"></div>

data () {
  return {
    htmlStr: 'Hello <span style="color: red">World</span>'
  }
}
Copy the code

How do I replace specified characters in a string with highlighted (HTML wrapped) characters?

Implementation: Highlight Hello in Hello World

const str = "Hello World" "Hello World".replace('Hello', '<span style="color: <span style="color: RGB (0, 0, 0); Red ">Hello</span> World // Note that the replace method matches only the first character. "Hello World Hello ABC ". Replace (/Hello/gi, '<span style="color: RGB (51, 51, 51); red">Hello</span>') // <span style="color: red">Hello</span> World <span style="color: red">Hello</span> abcCopy the code

string-associativesplitWith an array ofjoin

var str = "Hello world hello Hello";

// ["", "" Hello world ", ""]
const arr = str.split("hello");

hello hello
arr.join("<span>hello</span>");
Copy the code

The specific implementation

1. Bind calls in list items

<template>
  <div class="search-suggestion">/ / input box<input type="text" v-model="searchText" />// List of suggestions<van-cell :key="index" v-for="(item, index) in suggestions" icon="search">* // bind calls in V-html<div slot="title" v-html="highlight(item)"></div>
    </van-cell>
  </div>
</template>

export default {
  data() {
    return {
      suggestions: [].// Array of associative words
      searchText: null// Enter the box bound value}}},Copy the code

2. Add a method to methods to handle highlighting

    highlight(text) {
      const highlightStr = `<span class="active">The ${this.searchText}</span>`;
      // Everything in the middle of the regular expression is treated as a match character, not as a data variable
      // RegExp regular expression constructor
      // Argument 1: Matches the pattern string, from which it creates a re object
      // Argument 2: matches the pattern to be written to a string
      const reg = new RegExp(this.searchText, 'gi');
      // text.replace(/ matching content /gi, highlightStr)
      return text.replace(reg, highlightStr);
    }
Copy the code