React String Replace

2.0.1 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

Demonstrates how to perform multiple chained string replacements on a single text string, transforming URLs, @-mentions, and hashtags into clickable React `<a>` elements, suitable for rendering within a React component.

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'));

view raw JSON →