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.
str = "Adam Sandler" const highLight = (param) => { conosle.log(param) } const wrapWordsInSpan = (str) => { const addedSpanToText = str.replace( /w+/g, `<span id="text-container" style="color: ${highLight(`{$&}`)}"}>$&</span>` );
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:
const wrapWordsInSpan = (str) => { const addedSpanToText = str.replace( /w+/g, match => `<span id="text-container" style="color: ${highLight(match)}"}>${match}</span>` ); return addedSpanToText; };
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:
const wrapWordsInSpan = (str) => { const addedSpanToText = str.replace( /w+/g, match => `<span id="text-container" style="color: ${highLight(match)}"}>${match}</span>` ); return addedSpanToText; }; const highLight = (param) => { return param === "Adam" ? "green" : "black"; }; const str = "Adam Sandler" console.log(wrapWordsInSpan(str));