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:
src="/project/5cba4b052195310084a3c394/file/5cdc5e59a1fefc007cd21b51"
to:
http://somedomain.com/user_files/5cba4b052195310084a3c394_5cdc5e59a1fefc007cd21b51
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: https://jsfiddle.net/alexfotios/o6wt4d2p/

No comments:

Post a Comment