Product
Introducing License Enforcement in Socket
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
react-string-replace
Advanced tools
The react-string-replace npm package allows you to easily search and replace parts of a string with React components. This is particularly useful for rendering dynamic content within strings, such as highlighting keywords, linking URLs, or embedding custom components.
Basic String Replacement
This feature allows you to replace a specific substring within a string with a React component. In this example, the word 'world' is replaced with a <strong> component.
const React = require('react');
const reactStringReplace = require('react-string-replace');
const text = 'Hello, world!';
const replacedText = reactStringReplace(text, 'world', (match, i) => (
<strong key={i}>{match}</strong>
));
console.log(replacedText); // ['Hello, ', <strong key="0">world</strong>, '!']
Replacing Multiple Substrings
This feature allows you to replace multiple occurrences of a substring within a string with a React component. In this example, all occurrences of the word 'Hello' are replaced with an <em> component.
const React = require('react');
const reactStringReplace = require('react-string-replace');
const text = 'Hello, world! Hello, universe!';
const replacedText = reactStringReplace(text, 'Hello', (match, i) => (
<em key={i}>{match}</em>
));
console.log(replacedText); // [<em key="0">Hello</em>, ', world! ', <em key="1">Hello</em>, ', universe!']
Replacing with Custom Components
This feature allows you to replace substrings matching a regular expression with custom React components. In this example, URLs are replaced with <a> components.
const React = require('react');
const reactStringReplace = require('react-string-replace');
const text = 'Visit https://example.com for more info.';
const replacedText = reactStringReplace(text, /https?:\/\/\S+/g, (match, i) => (
<a href={match} key={i} target="_blank" rel="noopener noreferrer">{match}</a>
));
console.log(replacedText); // ['Visit ', <a href="https://example.com" key="0" target="_blank" rel="noopener noreferrer">https://example.com</a>, ' for more info.']
react-replace is a similar package that allows you to replace parts of a string with React components. It offers a straightforward API for performing replacements, but it may not be as flexible as react-string-replace in terms of handling complex replacement logic.
react-text-replace is another alternative that focuses on replacing text within strings with React components. It provides a simple API and is easy to use, but it may lack some of the advanced features offered by react-string-replace.
A simple way to safely do string replacement with React components. Zero dependencies.
Aka turn a string into an array of React components
yarn add react-string-replace
First, import the lib. Both require
and import
are supported.
import reactStringReplace from 'react-string-replace';
// OR
const reactStringReplace = require('react-string-replace')
Examples will use import
since it is more common in the React ecosystem.
import reactStringReplace from 'react-string-replace';
reactStringReplace('whats your name', 'your', (match, i) => (
<span>{match}</span>
));
// => [ 'whats ', <span>your</span>, ' name' ]
// Note that indexing [i] here starts at 1, not 0
// If you need to change this behavior for now try the workaround:
let count = -1;
reactStringReplace("the more the better", "the", (match, i) => (
count ++
<span>{match}</span>
));
Highlight all digits within a string by surrounding them in span tags:
reactStringReplace('Apt 111, phone number 5555555555.', /(\d+)/g, (match, i) => (
<span key={i} style={{ color: 'red' }}>{match}</span>
));
// =>
// [
// 'Apt ',
// <span style={{ color: 'red' }}>111</span>,
// ', phone number ',
// <span style={{ color: 'red' }}>5555555555</span>,
// '.'
// ]
import reactStringReplace from 'react-string-replace';
const HighlightNumbers = React.createClass({
render() {
const content = 'Hey my number is 555-555-5555.';
return (
<div>
{reactStringReplace(content, /(\d+)/g, (match, i) => (
<span key={i} style={{ color: 'red' }}>{match}</span>
))}
</div>
);
},
});
You can run multiple replacements on one string by calling the function multiple times on the returned result. For instance, if we want to match URLs, @-mentions and hashtags in a string we could do the following:
import reactStringReplace from 'react-string-replace';
const text = 'Hey @ian_sinn, check out this link https://github.com/iansinnott/ Hope to see you at #reactconf';
let replacedText;
// Match URLs
replacedText = reactStringReplace(text, /(https?:\/\/\S+)/g, (match, i) => (
<a key={match + i} href={match}>{match}</a>
));
// Match @-mentions
replacedText = reactStringReplace(replacedText, /@(\w+)/g, (match, i) => (
<a key={match + i} href={`https://twitter.com/${match}`}>@{match}</a>
));
// Match hashtags
replacedText = reactStringReplace(replacedText, /#(\w+)/g, (match, i) => (
<a key={match + i} href={`https://twitter.com/hashtag/${match}`}>#{match}</a>
));
// => [
// 'Hey ',
// <a href='https://twitter.com/ian_sinn'>@ian_sinn</a>
// ', check out this link ',
// <a href='https://github.com/iansinnott/'>https://github.com/iansinnott/</a>,
// '. Hope to see you at ',
// <a href='https://twitter.com/hashtag/reactconf'>#reactconf</a>,
// '',
// ];
See the example/
directory for a runnable example.
I wanted an easy way to do string replacement similar to String.prototype.replace
within React components without breaking React's built in string escaping and XSS protection. This meant standard string replacement combined with dangerouslySetInnerHTML
was out of the question.
Type: string|array
The string or array you would like to do replacement on.
NOTE: When passed an array this is the same as running the replacement on every string within the array. Any non-string values in the array will be left untouched.
Type: regexp|string
The string or RegExp you would like to replace within string
.
NOTE: When using a RegExp
you MUST include a capturing group. (/(hey)/g
is ok, /hey/g
is not.)
Example: Replace all occurrences of 'hey'
with <span>hey</span>
reactStringReplace('hey hey you', /(hey)/g, () => <span>hey</span>);
Type: function
The replacer function to run each time match
is found. This function will be passed the matching string and an index
which can be used for adding keys to replacement components if necessary. Character offset
identifies the position of match start in the provided text.
const replacementFunction = (match, index, offset) => <span key={index}>{match}</span>;
reactStringReplace('hey hey you', /(hey)/g, replacementFunction);
With v1.0.0 the API is considered stable and should be considered production ready. Pull requests are still welcome but there is currently no intent to make changes to this lib other than bug fixes (please submit an issue if you find something!).
For details on API tests see the tests file.
MIT © Ian Sinnott
FAQs
String#replace for React components
We found that react-string-replace demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.
Product
We're excited to introduce Socket Optimize, a powerful CLI command to secure open source dependencies with tested, optimized package overrides.