How to highlight text in a string

Vue and Quasar frameworks

String:

"Lorem ipsum dolor sit amet CONSECTETUR adipiscing elit"

Template

The following code does not work

<span:class="[highlight]">
{{ highlightSearchExpression(string) }}
 />

Using v-html (works inconsistently; merge search word with other words)

<span
  v-html="highlightSearchExpression(string)"
  :class="[highlight]"
/>

Method

highlightSearchExpression: function (str) {
  let searchWords = 'CONSECTETUR';

  if (str && searchWords) {
    //In case the search expression contains multiple words
    let searchValues = searchWords.toLowerCase().trim().split(" ");

    let pattern = new RegExp(`(.)(${searchValues.join("|")})`, "gi");
    let replacement = '$1<span class="highlight">$2</span class="highlight">';

    return str.replace(pattern, replacement);

  } else {
    return str;
  }
}

CSS

.highlight {
  color: #000000;
}

PROBLEM TO SOLVE:

Expected

Lorem ipsum dolor sit amet CONSECTETUR adipiscing elit

Returned

Lorem ipsum dolor sit ametCONSECTETURadipiscing elit

>Solution :

Your code appears to work. See snippet below! There must be something else going on.

const str = "Lorem ipsum dolor sit amet CONSECTETUR adipiscing elit";

const highlightSearchExpression = function (str) {
      let searchWords = 'CONSECTETUR';
    
      if (str && searchWords) {
        //In case the search expression contains multiple words
        let searchValues = searchWords.toLowerCase().trim().split(" ");
    
        let pattern = new RegExp(`(.)(${searchValues.join("|")})`, "gi");
        let replacement = '$1<span class="highlight">$2</span class="highlight">';
    
        return str.replace(pattern, replacement);
    
      } else {
        return str;
      }
    }

document.querySelector('#result').innerHTML = highlightSearchExpression(str);
.highlight {
  color: $000000;
  font-weight: bold;
  background-color: yellow;
}
<div id="result"></div>

Leave a Reply