1.1.1 • Published 1 year ago

react-string-replace v1.1.1

Weekly downloads
79,935
License
MIT
Repository
github
Last release
1 year ago

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

@thesaurus/components@cangir/gatsby-blog-corephoenix-shared@i1r0/gatsby-theme-nehalemdemio-browser-viewerwps-driver-reactmedbelle-ui-v6@roman-hotsiy/redocly-dev-portalcontrolled-react-lazyloggrossjsreact-formula-fieldobyte-qr-button-test21@everything-registry/sub-chunk-2615sandcastle-uirl-react-dashboardrl-react-generic-dashboardrl-react-generic-tablerl-react-loginredoc-dev-docssearchreplace-ocesellboot-library-componentsrhclientutopia-uilinklogm7kvqbe1-react-component-librarykoleznevdfgsdfgfsdgsdfhxdl-im-yx-uiguricomponentjoplin-plugin-joplin-batchmbo-sdkopen-source-lawpool-scratch-guipoe-components-itemnemeeting-core-sdkperitextphosphorus-corereact-datocmsreact-combilazylogreact-eagerlogreact-input-suggestionsreact-lazylogreact-lazylog-adjustedreact-lazylog-lightreact-lazylog-timestampsreact-lazylog-xobyte-qr-buttonreact-miotech-lazylogreact-misc-toolboxreact-native-tempssreact-native-twemojisqui-anzoslashr-reactsoba-visualization@akinon/next@baronbeans/gatsby-theme-medal@baradm100/gatsby-theme-admonation@blacksparrow/gatsby-theme-blacksparrow@britishlibrary/component-library@acciosolutions/react-logviewer279map-core@ecnft/orbis-component@inframe/web@innatical/markdown@kriskaminski/gatsby-theme-krishalem@local-civics/candid-ui@mantlemachine/ryft-kit@newcoin-foundation/iosdk@ndustrial/nd-react-charting@newstackdev/iosdk@nehalist/gatsby-theme-nehalem@factiverse/design-system@farmerconnect/farmerconnect-ui@melloware/react-logviewer@meniga/ui@kalonys/i18n@intellihr/ui-components@josh.chou/rasa-webchat@kolloqe/widget-en@jpmorgan-payments/embedded-banking-components@jpmorgan-payments/embedded-finance-components@jesusjimenezg/react-lazylog@kabartolo/gatsby-theme-chicago-docs@morphysm/react-chat-widget@redocly/developer-portal@sssoflyyy/react-logs@onebasket/storefront-ui-react@onebasket/shared-ui-react@pil0t/gatsby-theme-airplane@notionfolio/utils@pipinosuke/gatsby-theme-nehalem@orbisclub/components@rocketseat/highlight-editor@zebrainy/react-commonapplication-experience@cs-chatbots/webchat-ui@dailybruin/lux@devbydylan/dbd-speech@defencedigital/react-component-library@cangir/gatsby-theme-cms-core@payroll-no-ui/header
1.1.1

1 year ago

1.1.0

3 years ago

1.0.0

3 years ago

0.5.1

3 years ago

0.5.0

3 years ago

0.4.4

6 years ago

0.4.3

6 years ago

0.4.2

6 years ago

0.4.1

7 years ago

0.4.0

8 years ago

0.3.4

8 years ago

0.3.3

8 years ago

0.3.2

9 years ago

0.3.1

9 years ago

0.3.0

9 years ago

0.2.2

9 years ago