Replace all substring matches in a string
Similar to String#replace()
, but supports replacing multiple matches. You could achieve something similar by putting the string in a RegExp
constructor with the global flag and passing it to String#replace()
, but you would then have to first escape the string anyways.
$ npm install replace-string
const replaceString = require('replace-string');
const string = 'My friend has a 🐑. I want a 🐑 too!';
replaceString(string, '🐑', '🦄');
//=> 'My friend has a 🦄. I want a 🦄 too!'
Returns a new string with all needle
matches replaced with replacement
.
Type: string
String to work on.
Type: string
String to match in input
.
Type: string | Function
Replacement for needle
matches.
If a function, it receives the following arguments; the needle
, the match count, and the input
:
replaceString('Foo 🐑 Bar', '🐑', (needle, matchCount, input, matchIndex) => `${needle}❤️`);
//=> 'Foo 🐑❤️ Bar'
Type: object
Type: number
Default: 0
Index at which to start replacing.
- execall - Find multiple
RegExp
matches in a string
MIT © Sindre Sorhus