iansinnott / react-string-replace

A simple way to safely do string replacement with React components
MIT License
652 stars 56 forks source link

Allow multiple replacements on a single string #2

Closed iansinnott closed 8 years ago

iansinnott commented 8 years ago

This is issue was raised in #1. There's currently no clean way to run multiple replacements on a single string. The example raised in #1 is a good one: Given the below string, we want to match and replace URLs, hashtags and @-mentions:

Hey @iansinnott, check this link https://github.com/iansinnott/ #github

I'm not yet sure what the ideal API should look like, but at the very least reactStringReplace should accept a an array is an argument, allowing multiple replacements on the same string.

const reactStringReplace = require('react-string-replace');
const originalTweet = 'Hey @iansinnott, check this link https://github.com/iansinnott/ #github';

// Match URLs
let reactReplacedTweet = reactStringReplace(originalTweet, /(https?:\/\/\S+)/, (match, i) => (
  <a href={match}>{match}</a>
));

// Match @-mentions
reactReplacedTweet = reactStringReplace(reactReplacedTweet, /(@\w+)/, (match, i) => (
  <a href={`https://twitter.com/${match}`}>@{match}</a>
));

// Match hashtags
reactReplacedTweet = reactStringReplace(reactReplacedTweet, /(#\w+)/, (match, i) => (
  <a href={`https://twitter.com/hashtag/${match}?src=hash`}>#{match}</a>
));