Replace character before date match

I want to replace the underscore that precedes a date in a string e.g.

thequick_brown_20210813_fox

To:

thequick_brown_red_20210813_fox

I.e. replace that underscore with _red_

This captures the date part: (20d{2})(d{2})(d{2})

And to replace I assume I can just use str.replace

But not sure how I can capture the underscore that precedes it.

Answer

You can try the following RegEx with Positive Lookahead:

/_(?=d{8})/

Where:

_ matches the character _

(?=d{8}) – Positive Lookahead

d – matches a digit (equivalent to [0-9])

{8} – matches the previous token exactly 8 times

var str = 'thequick_brown_20210813_fox';
var patt = /_(?=d{8})/;
str = str.replace(patt, '_red_');
console.log(str);