react-markup-string
v1.1.3
Published
Find a specified string from the entire string, and replace it with a specified JSX.Element
Downloads
4
Maintainers
Readme
react-markup-string
Find a specified string from the entire string, and replace it with a specified JSX.Element
Installation
npm i react-markup-string
Usage
For example, if you want to replace a url in a string with <a>
JSX.Element
You can write your code with Markup component like this (TypeScript) (see in CodeSandbox)
const text = 'This url https://test.com should be replaced';
const regExp = /https?:\/\/[a-zA-Z0-9/.?_%=\\-]+/g;
const markuper = (matchText: string, key: number) => <a href={matchText} key={key}>{matchText}</a>;
const markuped = (
<Markup regExp={regExp} markuper={markuper}>
{text}
</Markup>
);
/**
* This url <a href="https://test.com">https://test.com</a> should be replaced
*/
If you also want to replace \n with <br>
JSX.Element
Add regular expression to regExp
and if statement to markuper()
const text = 'https://test.com\nhttps://example.com';
// Add \n with |
const regExp = /https?:\/\/[a-zA-Z0-9/.?_%=\\-]+|\n/g;
// Add if statement to mark up the text with different elements
const markuper = (matchText: string, key: number) => {
if (matchText.startsWith('http')) {
return (
<a href={matchText} key={key}>
{matchText}
</a>
);
} else {
return <br key={key} />;
}
};
const markuped = (
<Markup regExp={regExp} markuper={markuper}>
{text}
</Markup>
);
Custom matcher
You can also use custom matcher. This is useful if there is some condition that is difficult to express in regular expression.
const text = 'https://test.net & https://forbidden.org';
const allowedDomains = ['test.net', 'example.com', 'experiment.xyz'];
const matcher = (text: string) => {
const regExp = /https?:\/\/([a-zA-Z0-9.]+)\/?[a-zA-Z0-9/.?_%=\\-]*/g;
const result: MatchResult[] = [];
let match: RegExpExecArray | null;
while ((match = regExp.exec(text)) !== null) {
if (allowedDomains.includes(match[1])) {
result.push({
index: match.index,
text: match[0]
});
}
}
return result;
};
const markuper = (matchText: string, key: number) => (
<a href={matchText} key={key}>
{matchText}
</a>
);
const markuped = (
<Markup matcher={matcher} markuper={markuper}>
{text}
</Markup>
);
/**
* <a href="https://test.net">https://test.net</a> & https://forbidden.org
*/