I have a simple output of a date that looks like the following:
May 16, 2022, 1:00 PM
what I want to do is to replace it with the following string:
May 16, 2022 at 1:00 PM
I found this regex: .replace(/,*$/, " at");
According to that answer, I should get my desired result but instead I receive the following:
May 20, 2022, 1:00 AM at
It simply appends at
at the end of the string. Can I please get some help on how to tweak the regex? JavaScript is not my strongest language and regex even less.
CodePudding user response:
You need a way to match the second comma but not the first.
One way is to use a negative lookahead to prevent a match if there is another comma further along in the string.
const output = "May 16, 2022, 1:00 PM";
console.log(output.replace(/,(?!.*,)/, " at"));
Your regex /,*$/
means match zero or more commas followed immediately by the end of the string - clearly that is not useful here.
CodePudding user response:
Assuming the string will never change, the comma you want to replace is always going to be the last one in the string. So you could write a function that splices then concatenates the strings around the index of the last comma, like so:
function format_date(s) {
const i = s.lastIndexOf(',');
return s.slice(0, i) " at" s.slice(i 1);
}
The regex you posted will not replace the last comma inside a string, but only the trailing commas at the very end of the string (even if there aren't any).
CodePudding user response:
Use split()
and replace()
:
const output = "May 16, 2022, 1:00 PM"
const wordReplace = output.split(" ")[2]
const result = output.replace(wordReplace, `${wordReplace.split(",")[0]} at`)
console.log(result)
CodePudding user response:
const regex = /(\d{4}), (\d :\d )/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(\\d{4}), (\\d :\\d )', 'gm')
const str = `May 16, 2022, 1:00 PM`;
const subst = `$1 at $2`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log(result);