2

I have string like: I agree with the <link>Privacy Policy</link> & <link>Terms of Use</link>;

I am trying to convert it into

I agree with the <Button onClick={..}>Privacy Policy</Button onClick={..}> & <Button>Terms of Use</Button>;

Expected Result:

enter image description here

What I have tried so far

After going through various resources on the internet I have implemented this method:

const updateLinks = ({content, component: Component}) => {
  const linkTexts = content.match(/<link>(.*?)<\/link>/g);
  const updatedLinkTexts = linkTexts.map(text => {
    const innerText = /<link>(.*?)<\/link>/g.exec(text);
    return <Button onClick={() => console.log("working")}>{innerText[1]}</Button>;
  });
  // Logic for non-link content
  return updatedLinkTexts;
}

Attempt Result:

enter image description here

I can also add the some messy lines of code in order to add the remaining non-link content. But I am looking for some more elegant solutions otherwise, I can use the last option of some more messy lines of code.

Note: Use of regex is optional. Non-regex solutions are also cool.

Feel free to comment down for clarifications, if needed.

Community
  • 1
  • 1
Manish Sundriyal
  • 611
  • 6
  • 16
  • A bit more context would be nice--why can you not change the source code directly? Having to [parse HTML](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) and re-build the correct DOM is a last-resort solution. – ggorlen Apr 14 '20 at 19:57
  • @ggorlen I am not sure how the reason behind this can help, anyways: I storing all the content (anything visible to the user) in my DB. Now when it comes to footer links. Instead of storing each word separately, I have stored it as a string, where the words to be highlighted are wrapped with a fake tag. – Manish Sundriyal Apr 14 '20 at 20:09
  • You mean you're storing your HTML fragments in a database? I've never heard of this sort of design before, and it seems to me like the seemingly small hurdle you're asking about might be the first in a long series of issues related to parsing HTML. Why not use server side rendering? – ggorlen Apr 14 '20 at 20:16
  • No, I think you misunderstood my requirements. Let me try that again: Just like in CMS systems I am storing all my content in DB. Now think of a footer text where some words will be used as an inner text for links and some not. I am storing my footer content like `By proceeding, you are agreeing to the Terms of service`. Where the text "Terms of service" will be highlighted as a link on which users can click. So when I fetch this cms content to client now I need to replace the link markers () with some actual component (Button in this case). – Manish Sundriyal Apr 14 '20 at 21:05

0 Answers0