Answer the question
In order to leave comments, you need to log in
Replace all matches in text with a link?
I get text (different each time) where there are [link name](link itself) constructs . For example, we have the following text
Lorem ipsum dolor sit [amet](link to amet) , consectetur adipiscing elit. Morbi maximus libero sapien, eu ornare enim sagittis ac. Suspendisse ut sodales ante. Mauris lacinia id libero sed aliquam. Mauris malesuada neque tincidunt metus fringilla ultricies. [Morbi](link to Morbi) et nisi eget lacus tincidunt viverra. Aenean quis nibh ut mauris tempor ultrices. Morbi eget aliquet erat. Morbi quis consequat justo. Suspendisse rhoncus sollicitudin aliquet. Proin tempor aliquam lacinia. Aenean elementum cursus risus at ultricies. Fusce [ac](link to ac) hendrerit justo, eget viverra risus. Donec volutpat tellus nec lacus ultrices dictum.
<Link to={link}>name of link</Link>
Answer the question
In order to leave comments, you need to log in
In general, I did this, I took a ready-made solution for Mardown React .
Embed code:
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import Markdown from 'react-markdown';
import { getPaymentURLByType } from 'utils/URLsCollections';
function RouterLink(text) {
return (
text.href.match(/^(https?:)?\/\//)
? <a href={text.href}>{text.children}</a>
: <Link to={getPaymentURLByType(text.href)}>{text.children}</Link>
);
}
class ParagraphComponent extends PureComponent {
static propTypes = {
caption: PropTypes.string,
text: PropTypes.string,
};
static defaultProps = {
caption: '',
text: '',
};
render() {
const { caption, text } = this.props;
return (
<div data-block>
<h3>{caption}</h3>
<Markdown
source={text}
renderers={{ link: RouterLink }}
/>
</div>
);
}
}
export default ParagraphComponent;
You need to search with a regular expression, a construct like:
[буквы/символы](буквы/символы)
// с регуляркой, к сожалению не подскажу, не силен
// зато подскажет StackOverflow
// https://stackoverflow.com/questions/37462126/regex-match-markdown-link
<Link to={link}>name of link</Link>
Cut the text into pieces with a regular expression corresponding to links (an important point: you need to put the entire expression in brackets, this will allow you to get the separators themselves in the resulting array - future links), bypass the resulting array - if the element matches the regular expression, make a link, no - leave it as it is . Like so .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question