Javascript replace/append statement

I’m looking for help with the following. I need to add a block at the end of a line if it does not already exist. The line could be in any of the following formats (M could be either 3 or 4, S could be and number):

M4S10000

S10000M4

M4 S10000

S10000 M4

I want to add the string “G4 P1” to the end of the line as long as it doesn’t already exist

M4S10000 – Append to become M4S10000 G4 P1
M4S10000 G4 P1 – Ignore the line and move on

Original line left out a few conditions:

gcode = gcode.replace(/(S[0-9]* M[3-4])|(M[3-4] S[0-9]*)/g, ‘$& G4 P1’);

I’m looking to expand it to cover with or without a space between S and M blocks

gcode = gcode.replace(/(S[0-9]* M[3-4])|(M[3-4] S[0-9])|
(M[3-4]S[0-9]
|S[0-9]*M[3-4])/g, ‘$& G4 P1’);

Next I would like to do is make sure we don’t add “G4 P1” if it’s already there