regexify-string
Strings decorator (by regex) with: React components, HTML tags etc.
perfectly works with: strings, html tags, react, react-native
Install
$ npm install --save regexify-string
or
$ yarn add regexify-string
API
regexifyString({ pattern, decorator, input })
pattern
Type: RegExp
decorator
Type: (match: string, index: number) => string | JSX.Element
match
string you would like to replace/decorate with somethingindex
index number of the current match
NOTE: Try do not forget to use keys for React collections if needed
input
Type: string
Usage
with strings
const result = regexifyString({
pattern: /\[.*?\]/gim,
decorator: (match, index) => {
return `<${match}>`;
},
input: 'some [text] with simple example',
});
console.log(result);
with index keys
const result = regexifyString({
pattern: /\[.*?\]/gim,
decorator: (match, index) => {
switch (index) {
case 0: return `<FIRST ${match}>`;
case 1: return `<SECOND ${match}>`;
case 2: return `<THIRD ${match}>`;
default: return match;
}
},
input: 'Important text with [first link] and [second link] and much more [links]',
});
console.log(result);
with html
const result = regexifyString({
pattern: /\[.*?\]/gim,
decorator: (match, index) => {
return <span>{match}</span>;
},
input: 'some [text] with simple example',
});
console.log(result);
with React / React Native components
regexifyString({
pattern: /\[.*?\]/gim,
decorator: (match, index) => {
return (
<Link
to={SOME_ROUTE}
onClick={onClick}
>
{match}
</Link>
);
},
input: someVariablWithData,
});
regexifyString({
pattern: /\[.*?\]/gim,
decorator: (match, index) => {
return <React.Fragment>{match}</React.Fragment>;
},
input: 'some [text] with simple example',
});
License
MIT © Artem Solovev