Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to highlight text in a string

Vue and Quasar frameworks

String:

"Lorem ipsum dolor sit amet CONSECTETUR adipiscing elit"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading