Home > Software design >  JavaScript RegEx Negative Lookbehind Without Doing a Negative Lookbehind in SuiteScript 2.x
JavaScript RegEx Negative Lookbehind Without Doing a Negative Lookbehind in SuiteScript 2.x

Time:02-12

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'.

CodePudding user response:

Are there any useful traits of the hour placeholder other than not following "nt?" I'm not sure what all of the templates look like, but maybe it always precedes a ":" (roughly)...or it always follows whitespace...or something else similar if those aren't true?

CodePudding user response:

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)

Regex demo

  • Related