const regex = /(?m)^([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Za-z][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Za-z][0-9][A-Za-z]?)))? ?[0-9][A-Za-z]{2}$/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?m)^([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Za-z][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Za-z][0-9][A-Za-z]?)))? ?[0-9][A-Za-z]{2}$', 'gm')
const str = `Ivy Cottage, Rockley,SN81RT
11 Brabourne Gardens, North Shields,NE299JB
2 Russell Gardens, Whitchurch,RG287AY
14 Red Barns, Newcastle Upon Tyne,NE12TP
1 Hollybank, Tamworth Road, Lichfield,WS149JE
69 Burnlee Road, Holmfirth,HD92PS
30 Cashio Lane, Letchworth Garden City,SG61AX
14 Cedartree Gardens, Whitley Bay,NE258XN
518A Victoria Road, Ruislip,HA40HD
9 Pear Avenue, Leeds,LS168GT
`;
const subst = `$0@`;
// 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