Capturing dates of a text using regular expression in javascript

2

I have a function that returns data in JSON and places it in certain places with jQuery. One of these data is text that contains a date range (Start and End).

Example of returned text:

ESPÍRITO SANTO - Status: This is how much the Brazilian has already paid taxes in the period from 01/01/2014 until 03/03/2014

In the above case I want to return only these two dates, 01/01/2014 and 03/11/2014.

I've already seen several examples in javascript of capturing texts between defined characters, but not capturing a text format (in this case a date) and returning just that.

So how can I return only these two dates? What function should I use?

    
asked by anonymous 11.03.2014 / 19:15

5 answers

3

Use regular expressions.

var datas = texto.match(/\b(\d+\/\d+\/\d+)\b/g);
console.log(datas); // output: [ "01/01/2014", "11/03/2014" ]

In this particular case you get all strings that contain three numeric strings separated by a slash ( / ).

    
11.03.2014 / 19:27
2

A regular expression to retrieve dates in the form dd/mm/aaaa is \d{2}\/\d{2}\/\d{4} .

In javascript, you can create the regular expression and then use the exec function to iterate over the found items;

Example:

var pat = /\d{2}\/\d{2}\/\d{4}/g;
var resultados = [];
var item;
while (item = pat.exec(str)) {
    resultados.push(item[0]);
}

Occurrences would be in the resultados array.

And by encapsulating everything into a function we can do this:

function getDatas(str) {
    var pat = /\d{2}\/\d{2}\/\d{4}/g;
    var resultados = [];
    var item;
    while (item = pat.exec(str)) {
        resultados.push(item[0]);
    }
    return resultados
}

See the example in jsfiddle

(do not forget to open your browser's console to see the output)

    
11.03.2014 / 19:29
1
var reg = /([0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4})/g;
var str = "Um texto com uma data aqui 01/01/2012 e mais uma aqui 03/04/2000";
var todasAsDatas = str.match(reg);

It is important to remember that g at the end of the regular expression specifies that all occurrences should be returned.

This expression allows dates as 1/9/2013, or 9/1/2013.

    
11.03.2014 / 19:39
0

If the format is always dd/mm/aaaa , the regular expression is very simple:

\d{2}\/\d{2}\/\d{4}

#

    

11.03.2014 / 19:28
0

I think it's important to limit the possible wrong expressions a bit. In the expression below I do not restrict the differences of days per month and leap year, nor do I limit a minimum year of beginning.

var reg = /(([0-2]{1}[0-9]{1}|3[0-1]{1})\/(0[0-9]{1}|1[0-2]{1})\/[0-9]{4})/g;
var str = "Um texto com uma data aqui 01/01/2012 mas essa data errada aqui não pegaria 32/13/2000";
var todasAsDatas = str.match(reg);
    
28.12.2016 / 12:04