简体   繁体   中英

How to replace a text in a string with anchor tag in reactjs

I have a string like: var str = 'I love stackoverflow';

I want to replace the stackoverflow text in with an anchor tag.

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:

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

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

Alternative solution with 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 . This library is specifically build to convert urls in plain string to anchor tags.
<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.

  2. Create a regex parser to convert links to anchor tags and then render them as dangerouslySetInnerHTML as suggested by Doug . As mentioned by Doug please be careful while using dangerouslySetInnerHTML as it can be used for XSS attacks if values aren't properly sanitized.

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.

You can replace the string like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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