Menu

#6 Locale-specific regexps in javascript

2.0
open
nobody
None
2016-11-30
2016-11-30
il--ya
No

While trying to do GB localization, I came across this code in hoam/javascript/default_library.js:

// I don't know why, but the string read in through the config lookup isn't
// matching correctly, even though it's the same regex.
//          if (Event.element(event).value.match (HOAM_countryLookup ('date|match'))) {
            if (Event.element(event).value.match (/^([01]\d)[\-\.\/]([0-3]\d)[\-\.\/](19\d{2}|20\d{2})$/)) {

There are other similar comments in other places. I managed to get it working, thought this might be useful for you. The problem here is that regex literals in javascript are different from string literals. So
/^.*$/ is not the same as "/^.*$/". When testing/replacing, you use either RegExp literal, or string literal without forward slashes, not string literals with formard slashes.
To get around this, I used the following code:

            var match = new RegExp(HOAM_countryLookup ('date|match').replace(/^\/|\/$/g, ''));
            if (Event.element(event).value.match (match)) {

Now I think this would work as well (but I haven't tested it):

            if (Event.element(event).value.match (HOAM_countryLookup ('date|match').replace(/^\/|\/$/g, ''))) {

On a side note, each HOAM_countryLookup generates request to the server and really slows things down, so I'm trying to keep them to minimum. In this particular function, I load match pattern once, then use it first for testing and then for replacement.

Discussion


Log in to post a comment.

MongoDB Logo MongoDB