Thursday, July 18, 2019

JavaScript substring replace with RegEx and backreferences

I wanted to find all substrings matching a pattern, extract certain parts of those substrings, use those substrings of substrings to build new strings and finally replace the matched substrings with those new strings.

Specifically, using pure JavaScript, I wanted to scan a long string containing HTML, find all strings like:
Basically, match all strings like the top one, extract the two substrings of interest (in red) and then combine them into a new string that should replace the originally matched string.

I used JavaScript RegEx processing with backreferences marking the substrings in red and it works pretty well. Check out the simple and efficient code here:

No comments:

Post a Comment