Skip to content
Advertisement

Passing $& in replace()-function to another function

This code will take str and put each word in a <span>. I want to add some functionality, so some words will be highlighted, but can’t figure out how to pass $& (which is a word) to the highLight function. Right now I have written {$&} which does not work.

JavaScript

Advertisement

Answer

You’re really close, but you have to pass a function as the second argument to replace if you want to use that value dynamically (for instance, to call highlight), like this:

JavaScript

The match => `<span id="text-container" style="color: ${highLight(match)}"}>${match}</span>` part is the function. It gets called with the matched text as an argument (the equivalent of the $& token in the string), which I’ve called match above (capture group values are subsequent arguments, details on MDN). What it returns gets used as the replacement:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement