javascriptregexreactjsrender-to-stringreact-dom-server

JavaScript: How to format a str.replace with ReactDOMServer.renderToString, using a captured element as a prop


I am trying to apply this regex

str.replace(/<L href=(.*?)>(.*?)<\/L>/g, ReactDOMServer.renderToString(<L href={$1}>$1</L>))

But it doesn't recognize the $1 that is in the href={$1} (says it is not defined), while it does appear in the second place and it shows it is correctly captured

How can I write it?

*So the problem is not with the regex, but with how can I use the captured variable as a parameter form the component


Maybe something like this?

($1, $2) => ReactDOMServer.renderToString(<L href={$1}>$1</L>)

Solution

  • Can be workarounded by not capturing the comas

    str.replace(/<L href="(.*?)">(.*?)<\/L>/g, ReactDOMServer.renderToString(<L href="$1">$1</L>))
    

    But isn't there a better way?