Home > front end >  Javascript Split and Match the pattern array
Javascript Split and Match the pattern array

Time:07-05

I am trying to get the pattern from a string in JavaScript, where my string is 01-01-2000 - 01-01-2010 here I want to make these both date separate like date1 = 01-01-2000 and date2 = 01-01-2010.

I have tried this code :

var date = "01-01-2000 - 01-01-2010";
var date2 = date.match(/([0-9]{2})-([0-9]{2})-([0-9]{4})/);
console.log(date2[0]);

output: 01-01-2000 [correct]

but I using console.log(date2[1]) it displaying 01 only.

Please help how to achieve the goal make this function.

expecting output :

date[0]: 01-01-2000
date[1]: 01-01-2010

CodePudding user response:

You can give a try to String.matchAll() which returns an iterator of all results matching a string against a regular expression, including capturing groups.

Demo :

var date = "01-01-2000 - 01-01-2010";
var date2 = [ ...date.matchAll(/([0-9]{2})-([0-9]{2})-([0-9]{4})/g) ];

for (const match of date2) {
    console.log(match[0])
}

CodePudding user response:

You Can use split instead If your date format is fixed.

var date = "01-01-2000 - 01-01-2010";
var date2 = date.split(" - ")
console.log(date2);

CodePudding user response:

if you want to work with pattern you only have to add the /g in the end for global search into the string:

var date = "01-01-2000 - 01-01-2010";
var date2 = date.match(/([0-9]{2})-([0-9]{2})-([0-9]{4})/g);
console.log(date2[0]);
console.log(date2[1]);

  • Related