I have a text (random text) like this one:
bla bla bla (name of link)[link] bla bla bla (name of link)[link]
I need to replace all of (name of link)[link]
with Link
React ponent:
<Link to={link}>name of link</Link>
What I want to see:
bla bla bla <Link to='/testRoute'>Test name</Link> bla bla bla <Link to='/testRoute'>Test name</Link>
(name of link)[link]
in the text can be absent, and can meet many times.
How can I replace all matches by in the text?
Any help would be greatly appreciated.
I have a text (random text) like this one:
bla bla bla (name of link)[link] bla bla bla (name of link)[link]
I need to replace all of (name of link)[link]
with Link
React ponent:
<Link to={link}>name of link</Link>
What I want to see:
bla bla bla <Link to='/testRoute'>Test name</Link> bla bla bla <Link to='/testRoute'>Test name</Link>
(name of link)[link]
in the text can be absent, and can meet many times.
How can I replace all matches by in the text?
Any help would be greatly appreciated.
Share Improve this question edited Sep 5, 2018 at 16:51 Igor Alemasow 4,9092 gold badges31 silver badges27 bronze badges asked Sep 5, 2018 at 15:22 IlyaIlya 1133 silver badges11 bronze badges 6- 1 Use String.replace with a regular expression. – pishpish Commented Sep 5, 2018 at 15:28
- I tried, but probably not absolutely true I used. It is possible to set an example on my text how to make it? – Ilya Commented Sep 5, 2018 at 15:30
- 4 Show us what you tried before asking us to do it for you. – larz Commented Sep 5, 2018 at 15:30
- I found [name of link] by text.replace(/[(.*?)]/g, ''), but I don't know what need to do for replace for pletely <Link to={link}>name of link</Link> immediately – Ilya Commented Sep 5, 2018 at 15:39
-
<Link to={link}>name of link</Link>
is JSX version of React ponent, you can't just replace(name of link)[link]
with<Link to={link}>name of link</Link>
string – Igor Alemasow Commented Sep 5, 2018 at 15:48
2 Answers
Reset to default 3Try to split bla bla bla (name of link)[link] bla bla bla (name of link)[link]
string into an array of substrings, so you will have the following array:
const arrayOfStrings = [
'bla bla bla',
'(name of link)[link]',
'bla bla bla',
'(name of link)[link]',
];
And then you can use .map()
to create new array with valid React elements:
arrayOfStrings.map((str, i) => {
const isLink = str === '(name of link)[link]';//of course you need to replace it with regex
if (isLink) {
const linkName = 'name of link';//replace it with regex, so you can get dynamic link name from str
const link = 'link';//replace it with regex, so you can get dynamic link from str
return <Link key={i} to={link}>{linkName}</Link>;
}
else {
return <span key={i}>{str}</span>;
}
});
You have to use regexify-string
(npm)
npm install --save regexify-string
regexifyString({
pattern: /\[.*?\]/gim,
decorator: (match, index) => {
return (
<Link
to={SOME_ROUTE}
onClick={onClick}
>
{match}
</Link>
);
},
input: 'Some initial string with [link]',
});