Extract a fragment of a variant string in Javascript

0

I have a date string such as: 1-Ene-2017 , the case is also presented that is as follows: 28-Ene-2017 , what I try to do is get the part of the month's chain that is: Ene .

So far I have not been able to get the chain I want, this is what I tried:

function formatDate(date) {  
        var MonthName=["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"];
        var MonthName2=["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
        alert("" + date.substring(date.indexOf('-') + 1, 6));
        var mes = "";
        for(i=0; i<12; i++) {
        	if(date.substring(date.indexOf('-') + 1, 6) == MonthName[i]) {
        		mes = MonthName2[i];
        	}
        }
        alert("MES: " + mes);
    }
formatDate('28-Ene-2017');
formatDate('1-Ene-2017');

They will have some idea of how to get the chain I want.

    
asked by TimeToCode 29.11.2017 в 20:30
source

2 answers

4

An alternative may be that you make a split('-') and you capture the index 1

var fecha = '01-Ene-2017';

var result = fecha.split('-')[1];

console.log(result);

The split what it does is cut a string for each character that is indicated within the quotation marks in this case ('-') and transforms it into a array .

In the example, the result of the split would be [01, Ene, 2017] and we access the index 1 of that array, which in this case is Ene .

    
answered by 29.11.2017 / 20:32
source
2

You could use regular expressions to get the month.

If you use the /[a-zA-Z]{3}/ pattern then you will capture the string that includes three letters (the month, since the rest are digits or are hyphens).

var patron = /[a-zA-Z]{3}/;

var date1 = "1-Ene-2017";
var date2 = "28-Feb-2017";

var mes1 = patron.exec(date1);
var mes2 = patron.exec(date2);

console.log(mes1);
console.log(mes2);
    
answered by 29.11.2017 в 21:03