Generate a link from a word in a string with react-linkify

163 views Asked by At

Is there a possibility to create a link from a word in a string of text?

Example string:

"This is the first sentence. This is the second sentence."

So the rendered HTML should look like this:

This is the first sentence. This is the second <a href="https://www.example.com">sentence</a>.

I want to create a link from the word "sentence" but only the second occurrence.

1

There are 1 answers

0
nfrasser On

This is possible with the linkify-react package (not react-linkify, as far as I know) along with the linkify-plugin-keyword package:

import Linkify from 'linkify-react';
import registerKeywords from 'linkify-plugin-keyword';

registerKeywords(['foo', 'bar', 'baz'])

// ...

<Linkify options={{ formatHref: { keyword: (kw) => `https://example.com/tags/${kw}` } }}>
  Any foo keywords here?
</Linkify>