From 3c419240925fe045ae0adb1debd6417fec843aae Mon Sep 17 00:00:00 2001 From: Timur Kozmenko Date: Sun, 15 Sep 2013 18:10:04 +0700 Subject: [PATCH] feat(#getParseRegexForToken): escape special RegExp characters to increase presicion of penalty calculation --- moment.js | 6 ++++-- test/moment/create.js | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/moment.js b/moment.js index e0792671d..1a10cfbd8 100644 --- a/moment.js +++ b/moment.js @@ -365,6 +365,9 @@ return units ? unitAliases[units] || units.toLowerCase().replace(/(.)s$/, '$1') : units; } + function regexpEscape(text) { + return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); + } /************************************ Languages @@ -697,7 +700,7 @@ case 's': return parseTokenOneOrTwoDigits; default : - return new RegExp(token.replace('\\', '')); + return new RegExp(regexpEscape(token.replace('\\', ''))); } } @@ -889,7 +892,6 @@ tokens = expandFormat(config._f, lang).match(formattingTokens); config._a = []; - for (i = 0; i < tokens.length; i++) { parsedInput = (getParseRegexForToken(tokens[i], config).exec(string) || [])[0]; if (parsedInput) { diff --git a/test/moment/create.js b/test/moment/create.js index 87bdb77ea..02742660e 100644 --- a/test/moment/create.js +++ b/test/moment/create.js @@ -293,7 +293,7 @@ exports.create = { }, "string with array of formats" : function (test) { - test.expect(15); + test.expect(16); test.equal(moment('11-02-1999', ['MM-DD-YYYY', 'DD-MM-YYYY']).format('MM DD YYYY'), '11 02 1999', 'switching month and day'); test.equal(moment('02-11-1999', ['MM/DD/YYYY', 'YYYY MM DD', 'MM-DD-YYYY']).format('MM DD YYYY'), '02 11 1999', 'year last'); @@ -310,6 +310,7 @@ exports.create = { test.equal(moment('13-14-1999', ['DD/MM/YYYY', 'MM/DD/YYYY']).format('MM DD YYYY'), '02 13 2000', 'either can be a month, day first format'); test.equal(moment('11-02-10', ['MM/DD/YY', 'YY MM DD', 'DD-MM-YY']).format('MM DD YYYY'), '02 11 2010', 'all unparsed substrings have influence on format penalty'); + test.equal(moment('11-02-10', ['MM.DD.YY', 'DD-MM-YY']).format('MM DD YYYY'), '02 11 2010', 'escape RegExp special characters on comparing'); test.equal(moment('13-14-98', ['DD MM YY', 'DD MM YYYY'])._f, 'DD MM YY', 'use two digit year'); test.equal(moment('13-14-1998', ['DD MM YY', 'DD MM YYYY'])._f, 'DD MM YYYY', 'use four digit year'); -- 2.47.2