2

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?

Kamil Naja
  • 6,267
  • 6
  • 33
  • 47
Yerlan Yeszhanov
  • 2,149
  • 12
  • 37
  • 67
  • Possible duplicate of [Highlight text using ReactJS](https://stackoverflow.com/questions/29652862/highlight-text-using-reactjs) – Kevin Martins Apr 24 '19 at 10:28

2 Answers2

2

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;
}
jo_va
  • 13,504
  • 3
  • 23
  • 47
0

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)

adiga
  • 34,372
  • 9
  • 61
  • 83