简体   繁体   English

JavaScript - 从 JSON 数组获取数据时,用锚标记替换字符串

[英]JavaScript - Replace a string with anchor tag while fetching data from JSON Array

I have encountered this problem while doing loop over array of objects.我在对对象数组进行循环时遇到了这个问题。 Consider I have below array of objects.考虑我有以下对象数组。

General : [
       {
          question: 'Whats you suggestion?',
          answer: "Before you go ahead and book one of our trusted developer, please read our FAQ.",
       },
       {
          question: 'Do you have guaranteed solution?',
          answer: 'Please let us know at hello@stackoverflow.com.',
       }
     ]

I am using map in my JSX (react application) something like this.我在我的JSX (反应应用程序)中使用map类似这样的东西。

General.map((faq, index) => (
        <details>
          <summary>{faq.question}</summary>
          <div>
            <Linkify>{faq.answer}</Linkify>
          </div>
        </details>
      ))}

Now I want the text hello@stackoverflow.com to render as html anchor tag.现在我希望文本hello@stackoverflow.com呈现为html锚标记。 I have done this through React Linkify .我通过React Linkify做到了这一点。 But how we can achieve this with pure javascript?但是我们如何用纯 javascript 实现这一点呢?

This will work for emails, but you'll need to work out the regex for urls and chain them.这适用于电子邮件,但您需要计算出 url 的正则表达式并将它们链接起来。 Hope it helps.希望能帮助到你。

General.map((faq, index) => {
  const emailRegex = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/g;
  const emailReplacer = "<a href='mailto:$1'>$1</a>";
  return (
    <details>
      <summary>{faq.question}</summary>
      <div>
        <div>
          {faq.answer.replace(emailRegex, emailReplacer)}
        </div>
      </div>
    </details>
  )
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM