简体   繁体   中英

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?

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; }

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM