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