React String Replace
react-string-replace is a lightweight JavaScript utility designed to safely replace substrings or regular expression matches within a given string or array, converting them into an array containing React components and strings. It is currently at stable version 2.0.1 and has seen active development, with recent tooling modernizations and breaking changes in major versions. The library's core differentiator is its ability to perform replacements suitable for React's rendering model without relying on `dangerouslySetInnerHTML`, thus maintaining React's built-in XSS protection. It offers a simple API for common tasks like highlighting text, converting URLs, or parsing mentions, and supports chaining for multiple replacement patterns. It has zero runtime dependencies and ships with TypeScript types, making it suitable for modern React applications.
Common errors
-
TypeError: Cannot read properties of undefined (reading 'split') OR TypeError: undefined is not an object (evaluating 'e.split')
cause This error typically occurs when a regular expression, due to complex patterns or multiple matching groups, results in `undefined` elements being generated by the internal `String.prototype.split` operation, which the library then attempts to process as a string.fixThis specific issue was largely addressed in `v1.1.0`. Ensure you are using `react-string-replace` `v1.1.0` or newer. If the problem persists, carefully review your regular expression for edge cases that might yield `undefined` in split results, or simplify the regex if possible to avoid ambiguous matches. -
Replacement callback `index` parameter gives unexpected values (e.g., 1, 3, 5 instead of 0, 1, 2)
cause This behavior indicates that you are likely using `react-string-replace` v1.x or an older version, where the `index` parameter was an internal array index, not a logical match count.fixUpgrade to `react-string-replace` v2.0.0 or higher to utilize the more intuitive 0-based logical index. If upgrading is not an immediate option, you will need to adjust your logic to account for the older `index` numbering scheme (e.g., `(index - 1) / 2` to derive a 0-based logical index from the v1.x behavior).
Warnings
- breaking The `index` parameter provided to the replacement callback function changed its behavior in v2.0.0. It now represents the logical match index (0, 1, 2...) instead of the internal array index (1, 3, 5...) used in v1.x.
- gotcha When using a `RegExp` for the `match` parameter, you **must** include at least one capturing group (e.g., `/(word)/g` instead of `/word/g`). Failing to do so can lead to unexpected behavior or incorrect replacements, as the library relies on capture groups for splitting.
- gotcha To apply multiple distinct string replacement rules to the same content, you must chain calls to `reactStringReplace`. Pass the output array (which contains strings and React elements) from one call as the input `string` parameter to the next call.
- gotcha When the `string` parameter is an array, `reactStringReplace` will only process and apply replacements to the string elements within that array. Any non-string elements (e.g., existing React components, numbers, null) will be left untouched and returned as-is in the output array.
Install
-
npm install react-string-replace -
yarn add react-string-replace -
pnpm add react-string-replace
Imports
- reactStringReplace
const reactStringReplace = require('react-string-replace');import reactStringReplace from 'react-string-replace';
Quickstart
import reactStringReplace from 'react-string-replace';
import React from 'react';
function ProcessedContent() {
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} target="_blank" rel="noopener noreferrer">
{match}
</a>
));
// Match @-mentions
replacedText = reactStringReplace(replacedText, /@(\w+)/g, (match, i) => (
<a key={match + i} href={`https://twitter.com/${match}`} target="_blank" rel="noopener noreferrer">
@{match}
</a>
));
// Match hashtags
replacedText = reactStringReplace(replacedText, /#(\w+)/g, (match, i) => (
<a key={match + i} href={`https://twitter.com/hashtag/${match}`} target="_blank" rel="noopener noreferrer">
#{match}
</a>
));
return <div>{replacedText}</div>;
}
// To use, render <ProcessedContent /> within a React component tree.
// For example:
// ReactDOM.render(<ProcessedContent />, document.getElementById('root'));