简体   繁体   English

如何用 reactjs 中的锚标记替换字符串中的文本

[英]How to replace a text in a string with anchor tag in reactjs

I have a string like: var str = 'I love stackoverflow';我有一个类似的字符串: var str = 'I love stackoverflow';

I want to replace the stackoverflow text in with an anchor tag.我想用锚标记替换stackoverflow文本。

I tried with replace but its not working.我尝试使用替换,但它不起作用。 Can someone advise.有人可以建议。

Consider first removing the word "stackoverflow" from the string, then render it with the anchor tag:考虑首先从字符串中删除单词"stackoverflow" ,然后使用锚标记呈现它:

const greeting = "I love stackoverflow";
const finalGreeting = greeting.replace('stackoverflow', '');

return <>
  {finalGreeting}
  <a href="https://stackoverflow.com">stackoverflow</a>
</>

Alternative solution with dangerouslySetInnerHTML :使用dangerouslySetInnerHTML的替代解决方案:

 const HelloStackOverflow = () => { const greeting = "stackoverflow is my love"; const finalGreeting = greeting.replace('stackoverflow', '<a href="https://stackoverflow.com">stackoverflow</a>'); return <span dangerouslySetInnerHTML={{ __html: finalGreeting }}/> } ReactDOM.render( <HelloStackOverflow />, document.getElementById('root') );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root" />

You have following solutions to your problem.您有以下问题的解决方案。

  1. Use 3rd party library like react-linkify .使用像react-linkify这样的第三方库。 This library is specifically build to convert urls in plain string to anchor tags.该库专门用于将纯字符串中的 url 转换为锚标记。
<Linkify>
 See source code at https://github.com/tasti/react-linkify/.
</Linkify>

This will convert the link to clickable links.这会将链接转换为可点击的链接。

  1. Create a regex parser to convert links to anchor tags and then convert the string into array of strings and links and then map that array in any paragraph or where ever you're thinking of displaying this text.创建一个正则表达式解析器以将链接转换为锚标记,然后将字符串转换为字符串和链接的数组,然后在任何段落或任何您想显示此文本的地方 map 该数组。

  2. Create a regex parser to convert links to anchor tags and then render them as dangerouslySetInnerHTML as suggested by Doug .创建一个正则表达式解析器以将链接转换为锚标记,然后按照 Doug 的建议将它们呈现为dangerouslySetInnerHTMLSetInnerHTML As mentioned by Doug please be careful while using dangerouslySetInnerHTML as it can be used for XSS attacks if values aren't properly sanitized.正如 Doug 所提到的,在使用dangerouslySetInnerHTML时请小心,因为如果没有正确清理值,它可以用于 XSS 攻击。

If you're heavily relying on converting plain string urls to anchor tags and adding another dependency is not an issue then I will suggest you to go with 1st one.如果您严重依赖将纯字符串 url 转换为锚标记并且添加另一个依赖项不是问题,那么我建议您使用第一个 go。

You can replace the string like this:您可以像这样替换字符串:

var originalText = "I love stackoverflow";
var changedText = originalText.replace("stackoverflow", "myself");

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

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