Fred J. Fred J. - 1 year ago 55
Javascript Question

reference a regex group number when optional bracket present

This javascript regex tries to convert


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

is producing


What did I get wrong? Thanks

Answer Source

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


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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download