0

Our organization's style guide specifies a date-time in this format: Dec. 31 08:45 a.m.. Our site runs Drupal, which is a PHP-based CMS. Its field formatting templates allow for date-formatting strings specified in the encoding which is defined in HPHP's date() function. It only offers a, which gives pm, and A, which gives me PM, but I don't see anything specifying one with periods.

Unfortunately, there is not an easy way to hook in to the platform to define a custom date format, so I figure the simplest way forward is to do a find-and-replace with javascript. What I want to do is replace instances in the format NN:NN am and NN:NN pm with NN:NN a.m., etc.

Regexes have never been my strong suit. I can match date time format well enough( [0-9][0-9]:[0-9][0-9] pm), but I don't know how to perform the proper replacement.

How can I replace am and pm with properly abbreviated version, when they follow a four-digit time format?

2
  • 1
    What have you tried so far? Please post the code you've written already. Commented Oct 23, 2018 at 19:45
  • @MarcM. Hello, what I've tried so far is what I have already posted in the question: [0-9][0-9]:[0-9][0-9] pm. I don't know how to do the replace part. Commented Oct 23, 2018 at 19:56

4 Answers 4

1
str.replace(/(\d{2}:\d{2}\s?a|p)(m)/, '$1.$2');
Sign up to request clarification or add additional context in comments.

Comments

1

An alternative is using the optional handler in the function replace to get the match string and replace the am or pm strings with a.m or p.m respectively.

let str = "Dec. 31 08:45 am",
    result = str.replace(/([\d][\d]:[\d][\d] am|pm)/, function(match) {
      return match.replace('am', 'a.m.').replace('pm', 'p.m.');
    });
    
console.log(result);

1 Comment

I think one replacement using str.replace(/([\d][\d]:[\d][\d]) ([ap])m/, "$1 $2.m.") can work by grouping the A and P together. I admit I haven't tested it extensively.
1

You can use the following regex and replacement pattern to do, what you want:

Regex: ([0-2][0-9]:[0-5][0-9]\s)(a|p)(m)

Replace: '$1$2.$3.'

How to use:

var text = 'Dec. 31 08:45 am';
text = text.replace(/([0-2][0-9]:[0-5][0-9] )(a|p)(m)/, '$1$2.$3.');

Comments

1
'Dec. 31 08:45 AM, Jan. 1 10:15 pm'.replace(/(\d{2}:\d{2}) (a|p)(m)/ig, (match, p1, p2, p3) => {
  return `${p1} ${p2}.${p3}.`.toLowerCase();
});

yields the result

Dec. 31 08:45 a.m., Jan. 1 10:15 p.m.

1 Comment

The i after the regular expression is needed to ignore case if the input could also be uppercase like AM, and PM. The g is for replacing all occurrences. Otherwise only the first will be replaced. The solution uses some modern syntax that may not work in an older browser.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.