Match all occurrences in string and replace it
Finds all occurrences in the string for given regex and replaces the value with a new string (using callback function).
Install
npm install match-replace-all
Usage
- Create a new RegExp object with
global
andmultiline
option. - Provide a callback that will receive match array and return a new string that will replace the original string.
- Callback can return
false
to skip replacement. - If the new value is same as original, no replacement is done.
const regex = '<a([^>]*)>([^<]+)</a>' 'gm'const string = 'testing <a>first</a> <a target="_blank">second</a>'// Add href attribute to link with the links valueconst newString = console
Result:
Result: testing <a href="http://first">first</a> <a href="http://second" target="_blank">second</a>