const regex = /(\[SM_g])([^[]*)(\[SM_h])((?=([,\.])|(\[SM_l])|( ?&\\?quot;)).*)?/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(\\[SM_g])([^[]*)(\\[SM_h])((?=([,\\.])|(\\[SM_l])|( ?&\\\\?quot;)).*)?', 'gm')
const str = `[SM_g]word[SM_h].[SM_l] "
[SM_g]word[SM_h][SM_l]"
[SM_g]word[SM_h]"[SM_l].
[SM_g]word[SM_h]".
[SM_g]word[SM_h][SM_l].
[SM_g]word[SM_h].
[SM_g]word[SM_h]
[SM_g]word[SM_h] ".
[SM_g]word[SM_h][SM_l] &\\quot;.
[SM_g]word[SM_h].[SM_l]"
[SM_g]word[SM_h]"[SM_l].
[SM_g]word[SM_h] ".`;
const subst = `\1\2\7\3`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions