I've put together a function in a custom module to handle trying to do a date/time formatting using the templates presented by NetSuite from the company preferences. However, I've had some trouble with handling the full name of the month and the hour in 12 hour format. If I use a negative lookbehind, it works just fine, but the problem is that it only works in scripts using 2.1, and there are too many in 2.0 to go around updating everything that needs this function from 2.0 to 2.1.
For example, these particular time templates:
Month D, YYYY
h:mm
The first will have proper output like:
February 11, 2022
But the second will have erroneous output:
h:15
I'm using the following RegEx to match the hour placeholder:
/^(?!nt)h/
And I know this works better where I can use it:
/(?<!nt)h/
I've tried searching around for a way to handle matching the "h" where it's not preceded by "nt", but they all keep pointing to the use of a negative lookbehinds to handle it, or are a bit unclear as to exactly how it's being done.
EDIT
Just to reduce confusion, the following are formats that could also be passed in to the function and need to be handled correctly:
YYYY/DD/MM h:m:s
MONTH DD, YYYY H-mm-ss
YYYYDDMMhms
YYYYDDMM-HHmmss
There's no one specific date/time template that can be passed in, so there's a specific need to be able to find H/h without it being a part of the word 'Month'.
You might use a capture group instead to capture what you want to keep, and match what you want to get out of the way.
The pattern matches nth that you don't want, and captures a h char.
In the code you could check if group 1 is present.
nth|(h)
For example in Javascript
const regex = /nth|(h)/gi;
const str = `Month D, YYYY
h:mm
February 11, 2022
h:15
YYYY/DD/MM h:m:s
MONTH DD, YYYY H-mm-ss
YYYYDDMMhms
YYYYDDMM-HHmmss`;
const result = str.replace(regex, function(m, g1) {
return g1 !== undefined ? "[" + g1 + "]" : m;
});
console.log(result);
You can use
/h(?!(?<=\bMonth)\b)/gi
See the regex demo. Details:
h - a h letter(?!(?<=\bMonth)\b) - a negativ lookahead that fails the match if immediatey to the eft of the current location there is a whole word Month.If you do not care if the word Month is a whole word, you can use
/h(?<!Month)/gi
See this regex demo.