0

I have the following code:

var splitter = (filterValue.length > 0 ? filterValue.match(/^\s*(<|>)?\s*(\d\d\/\d\d\/\d{4})\s*\-?\s*(\d\d\/\d\d\/\d{4})?\s*$/).slice(1) : '');

Where filterValue could be:

01/01/2013

> 01/01/2013

< 01/01/2013

01/01/2013 - 01/01/2013

And then I split these into chunks like:

    var string1 = (splitter.length > 0 ? splitter[0] : '');
    var string2 = (splitter.length >= 2 ? splitter[1] : '');
var string3 = (splitter.length >= 3 ? splitter[2] : '');
var string4 = (splitter.length < 4 ? splitter[3] : '');

string1 would be either '', '>', '<', '' for the above examples.

string2 would always be the first date

string3 would be either '' or '-' if the dash is present between two dates

string4 would be the last date.

However I can't get the last scenario to work. So presume I have a problem in my regex for handling this. Can anyone see the problem?

Fiddle: http://jsfiddle.net/7LR49/1/

I'm getting:

undefined
01/01/2013
01/01/2013
undefined

When I should be getting:

undefined
01/01/2013
-
01/01/2013

and doing a console on splitter shows:

[undefined, "01/01/2013", "01/01/2013"]

So the last 3rd key isn't actual being picked up by the regex. And instead getting the 4th in its place.

Cameron
  • 27,963
  • 100
  • 281
  • 483
  • I don't see how that particular error results from this code. Could you provide a fiddle that exhibits your error? – Tibos Nov 11 '13 at 16:35
  • Added a fiddle with examples of what I'm getting and what I should be getting. Thanks. – Cameron Nov 11 '13 at 16:50

2 Answers2

2

A couple of fixes:

  • Your regex was not capturing the dash as third group. So I changed it.

From: /^\s*(<|>)?\s*(\d\d\/\d\d\/\d{4})\s*\-?\s*(\d\d\/\d\d\/\d{4})?\s*$/
To....: /^\s*(<|>)?\s*(\d\d\/\d\d\/\d{4})\s*(\-)?\s*(\d\d\/\d\d\/\d{4})?\s*$/
Changed: .................................^..^

  • And your condition was not evluating to true so you would ignore the last group's value:

From: var string4 = (splitter.length < 4 ? splitter[3] : '');
To....: var string4 = (splitter.length < 5 ? splitter[3] : '');
Changed: ..............................^

Output now:

undefined
01/01/2013
-
01/01/2013 

Your fiddle, updated: http://jsfiddle.net/7LR49/2/

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
0

The following works for me:

function getMatches(string, regex, index) {
    index || (index = 1); // default to the first capturing group
    var matches = [];
    var match;
    while (match = regex.exec(string)) {
        matches.push(match[index]);
    }
    return matches;
  }
  var str = "> 01/01/2013 - 02/01/2013";
  var regex = /\b(\d\d\/\d\d\/\d\d\d\d)\b/g;
  var matches = getMatches(str, regex, 1);
  alert(matches[0]);
  alert(matches[1]);

OUTPUT:

01/01/2013
02/01/2013

The method is taken from here

Community
  • 1
  • 1
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129