Home > Blockchain >  RegEx: replace two group characters global from string
RegEx: replace two group characters global from string

Time:08-08

Is there a more elegant/better way of performing the below replacement, I want to split AM and PM from all words and add a comma so is rendered as following

Monday, AM
Monday, PM
Wednesday, AM
Wednesday, PM
Thursday, AM
Friday, AM
Friday, PM

<script>
let str = "MondayAM,MondayPM,TuesdayAM,WednesdayAM,ThursdayAM,ThursdayPM";
str = str.replace(/,/g,'\n').replace(/AM/g,", AM").replace(/PM/g,", PM")
console.log(str);
document.write("<pre>" str "</pre>")
</script>

CodePudding user response:

You can use group replacement, replace AM or PM, with the , $1, $1 refers to AM or PM found in the text.

let str = "MondayAM MondayPM TuesdayAM WednesdayAM ThursdayAM ThursdayPM";
str = str.replace(/(AM|PM)/g, ", $1")
console.log(str);

CodePudding user response:

For both data formats with a comma or a space:

([^\s,] )([AP]M)\b[, \t]*

Explanation

  • ([^\s,] ) Capture group 1, match 1 non whitespace chars other than a comma
  • ([AP]M) Capture group 2, match either AM or PM
  • \b A word boundary to prevent a partial word match
  • [, \t]* Match optional spaces, tabs or comma

Regex demo

const regex = /([^\s,] )([AP]M)\b[, \t]*/g;
const str = `MondayAM MondayPM TuesdayAM WednesdayAM ThursdayAM ThursdayPM
MondayAM,MondayPM,TuesdayAM,WednesdayAM,ThursdayAM,ThursdayPM
`;
const subst = `$1, $2\n`;
console.log(str.replace(regex, `$1, $2\n`));


Another variation matching only leading chars A-Za-z and assuming there is only a comma as a separator:

([A-Z][a-z] )([AP]M)\b,?

Regex demo

CodePudding user response:

Yes, you can do it in a single regex. Since you're doing the same thing with both "AM" and "PM", you can write a regex that captures either and uses $N expression instead of constant value, to put the captured group back to the output string.

You can also replace "," with a new line in the same expression. (I used (,|$) which means a comma or end of string, because there is no comma after the last entry.)

<script>
let str = "MondayAM,MondayPM,TuesdayAM,WednesdayAM,ThursdayAM,ThursdayPM";
str = str.replace(/([AP]M)(,|$)/g,", $1\n")
console.log(str);
document.write("<pre>" str "</pre>")
</script>

  • Related