Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

261
Views
RegEx: replace two group characters global from string

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>

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!