• Stars
    star
    605
  • Rank 74,072 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 9 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A simple way to safely do string replacement with React components

React String Replace

react-string-replace.js on NPM

A simple way to safely do string replacement with React components. Zero dependencies.

Aka turn a string into an array of React components

Install

yarn add react-string-replace

Usage

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.

Simple Example

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

More realistic example

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>,
//   '.'
// ]

Within a React component

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>
    );
  },
});

Multiple replacements on a single string

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>,
//   '',
// ];

Full Example

See the example/ directory for a runnable example.

Why?

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.

API

reactStringReplace(string, match, replacementFunction)

string

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.

match

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

replacementFunction

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

API Stability

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.

License

MIT © Ian Sinnott

More Repositories

1

alfred-maestro

An Alfred workflow to execute Keyboard Maestro macros.
Go
409
star
2

jstz

🌐Timezone detection for JavaScript
JavaScript
172
star
3

react-static-webpack-plugin

Build full static sites using React, React Router and Webpack (Webpack 2 supported)
JavaScript
157
star
4

react-static-boilerplate

A boilerplate for building static sites with Webpack 2, React and React Router
JavaScript
108
star
5

prompta

ChatGPT UI that is keyboard-centric, mobile friendly, can syncs chat history across devices and search past conversations.
Svelte
30
star
6

asciilib

(ノ◕ヮ◕)ノ*:・゚✧ A library of ascii faces and kaomoji
JavaScript
18
star
7

rxjs-dash-docset

RxJS 5 documentation for Dash
JavaScript
15
star
8

browser-gopher

Search, aggregate, backup your browsing history from the command line.
Go
14
star
9

notion-utils

TypeScript
9
star
10

asciilib-workflow

Quickly search through ascii faces and kaomoji (ノ◕ヮ◕)ノ*:・゚✧
JavaScript
9
star
11

zazu-emoji

⚡ Fast, offline emoji search for Zazu
JavaScript
8
star
12

jekyll-post

A tool for managing Jekyll from the command line
JavaScript
8
star
13

react-static-presentation

The Slide deck and examples for my React Static talk
JavaScript
8
star
14

darkly-darker-theme

A dark Chrome theme
JavaScript
7
star
15

one-dark-tab

Like OneTab, but darker.
JavaScript
7
star
16

nightmare-ava-example

JavaScript
6
star
17

webpack-base-project

A minimal Webpack project to teach you how to set up a new project
JavaScript
6
star
18

things-2do-importer

Import 2Do tasks into Things 3
Python
6
star
19

mailstring

Generate mailto strings for fun and profit. Also a React component 📤
JavaScript
5
star
20

zazu-dark-theme

🕶 A simple, dark theme for Zazu
CSS
5
star
21

shirt

👕 Put a shirt on that data! Simple algebraic data types
JavaScript
4
star
22

iansinnott.github.io

The blog of Ian SInnott
HTML
4
star
23

app-time

🌟 Build complete, wonderful, beautiful apps with one dependency. Compile to static HTML files with a single command.
JavaScript
4
star
24

google-sheets-backend

JavaScript
3
star
25

express-middleware-lecture

Source code and writeup for my lecture on Express middleware
JavaScript
3
star
26

stylite

🎨 A super lightweight style editor. Apply any styles you want to any site.
JavaScript
3
star
27

chinese-common-wordlist-pleco-decks

JavaScript
2
star
28

real-time-stack

JavaScript
2
star
29

imessage-backup-helpers

JavaScript
2
star
30

react-boilerplate

React + Webpack + Hot Reloading 🎉
JavaScript
2
star
31

bitbucket-cli

A CLI for BitBucket
JavaScript
2
star
32

asciilib-site

The website for asciilib
TypeScript
2
star
33

slush-express-isinn

Generate Express apps with Slush.
CSS
1
star
34

markdown-to-csv

JavaScript
1
star
35

emoji-annotations

JavaScript
1
star
36

character-frequency-workflow

JavaScript
1
star
37

gatsby-notion

TypeScript
1
star
38

url-spider

TypeScript
1
star
39

jquery-ui-dropdown

A simple dropdown widget for jQuery UI
JavaScript
1
star
40

trimstring

🔪 Neatly trim template strings
JavaScript
1
star
41

mini-redux

A simple imitation of Redux implemented in a single React component
JavaScript
1
star
42

sqlite-syncta

Experimenting with syncing sqlite databases
Go
1
star
43

eslint-config-zen

An ESLint config for use with the latest ESNext features, React and Flow
JavaScript
1
star
44

electron-auto-update

TypeScript
1
star
45

addr.fyi

JavaScript
1
star
46

how-the-web-works

An over simplified explanation of how the web works
JavaScript
1
star
47

history-to-finda

Clojure
1
star
48

notedown

A note-taking app...
JavaScript
1
star
49

record-video

An example of recording on mobile with the front-facing camera.
TypeScript
1
star
50

baby-lisp-interpreter

Clojure
1
star
51

try-instantdb

Trying out InstantDB
TypeScript
1
star
52

next-tailwind-typescript-starter

TypeScript
1
star
53

authguardian-react-starter

JavaScript
1
star
54

lab.iansinnott.com

🔬 Where I run experiments and learn by doing
JavaScript
1
star