🧶 Safely replace any part of a string with anything. Example: useful for replacing substrings with JSX in React. Replaces https://github.com/rpearce/highlightify and descendent of ideas for trying to fix https://github.com/iansinnott/react-string-replace
BSD-3-CLAUSE License
$ npm i @rpearce/flexible-string-replace
or
$ yarn add @rpearce/flexible-string-replace
flexible-string-replace
mirrors the functionality of
String.prototype.replace
with the following exceptions:
[ * ]
– an Array of whatever type your Replacement
is(Pattern, Replacement, String)
so that if you'd likecurry
the function and partially applyNote: while these examples use some JSX, your matching function can return whatever you like.
import flexibleStringReplace from '@rpearce/flexible-string-replace'
const str = 'The rain in Spain falls mainly on the plain. Spain is nice.'
const searchText = 'spain'
const replacement = (match, offset) => <mark key={offset}>{match}</mark>
// usage with RegExp pattern
const pattern = new RegExp(searchText, 'igm')
flexibleStringReplace(pattern, replacement, str)
// [
// 'The rain in ',
// <mark>Spain</mark>,
// ' falls mainly on the plain. ',
// <mark>Spain</mark>,
// ' is nice.'
// ]
// usage with RegExp pattern and string Replacement
const pattern = 'Spain'
flexibleStringReplace(pattern, 'foobar', str)
// [
// 'The rain in ',
// 'foobar',
// ' falls mainly on the plain. ',
// 'foobar',
// ' is nice.'
// ]
// usage with String pattern (no match)
const pattern = 'spain'
flexibleStringReplace(pattern, replacement, str)
// ["The rain in Spain falls mainly on the plain. Spain is nice."]
// usage with String pattern (match)
const pattern = 'Spain'
flexibleStringReplace(pattern, replacement, str)
// [
// 'The rain in ',
// <mark>Spain</mark>,
// ' falls mainly on the plain. Spain is nice.',
// ]
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!