Fred J. Fred J. - 5 months ago 6
Javascript Question

reference a regex group number when optional bracket present

This javascript regex tries to convert

href=/m3/whaever
to
href=http://abc.xyz.com/m3/whatever


const link = 'http://abc.xyz.com';
return html.replace(/([(href=)|(src=")|(src=)])(\/m3)/g, '$1' + link + '$5');


is producing

href=http://abc.xyz.com$5


What did I get wrong? Thanks

Answer

[...] is used to specify character classes, not to group alternatives.

[(href=)|(src=")|(src=)]

matches a single character that's any of the characters inside the brackets, i.e. it's equivalent to

[cefhrs()="]

Use () to group alternatives.

return html.replace(/(href=['"]?|src=['"]?)(\/m3)/g, '$1' + link + '$2');

The ? makes the quote characters optional, you don't need separate alternatives for them.

Comments