Yerlan Yeszhanov
Yerlan Yeszhanov

Reputation: 2439

how to highlight text in string?

I have this kind of string "Hello , I'm looking for /# job as a teacher #/" . Everything in this /# ----#/ has to be highlighted.

Here what I'm doing:

highlightMessage(message) {
    if (message.match(/\/#\s*|\s*#\//g)) {
      console.log(message.replace(/\/#\s*|\s*#\//g, `<span className='yellow'>$1</span>`))
    }
  }

but my output is:

Hello , I'm looking for <span className='yellow'>$1</span>job as a teacher<span className='yellow'>$1</span>

Where I'm doing mistake?

Upvotes: 2

Views: 376

Answers (2)

adiga
adiga

Reputation: 35202

You could use the regex \/#(.*)#\/ to get everything within /# #/ to a capturing group and replace it with a <span> wrapper around it.

function highlightMessage(message) {
  if (/\/#.*#\//g.test(message)) {
    document.body.innerHTML += message.replace(/\/#(.*)#\//g, `<span class='red'>$1</span>`)
  }
}

highlightMessage("Hello , I'm looking for /# job as a teacher #/")
.red { color: red }
<body></body>

(class is used instead of className for demo purposes)

Upvotes: 0

jo_va
jo_va

Reputation: 13964

Use (.*?) to create a group that matches anything non-greedily between the hashes, then pass an arrow function as second argument to access the matched group and return the value to replace it with. The group can be accessed in the second argument of this arrow function:

function highlight(message) {
  return message.replace(/\/#\s*(.*?)\s*#\//g,
    (_, g) => `<span className='yellow'>${g}</span>`);
}

You can even pass the replacement function as an argument to customize the replacement if needed.

Here is an example with multiple replacements in the same string:

function highlight(message, replacer = s => `<span class="bold">${s}</span>`) {
  return message.replace(/\/#\s*(.*?)\s*#\//g, (_, g) => replacer(g));
}
  
document.body.innerHTML += highlight("Hello , /#I'm#/ looking for /# job as a teacher #/");
document.body.innerHTML += highlight("<br>Nothing to replace here");
document.body.innerHTML += highlight("<br>You can pass a custom /#replacer function #/ too", s => '😀' + s.toUpperCase() + '😀');
.bold {
  font-weight: bold;
  font-size: 20px;
}

Upvotes: 2

Related Questions