How To Check If Numbers Precedes A More "verbal" String?
Given a var dateText; which outputs any single of this: dateText = '12-5 November 17 May 1954'; dateText = '12 January 1976'; dateText = '12 22 March 1965'; And after doing: for(v
Solution 1:
If we can assume the only non-numeric/whitespace/punctuation characters in the input will be month names, and the format is always as you describe, then the simplest solution may be to split
on month names. For example:
const input = '12-5 November 17 May 1954';
console.log(input.split(/\s+([a-z]+)\s+/i));
// => [ '12-5', 'November', '17', 'May', '1954' ]
Since we know that the result will always consist of one or more day-month pairs followed by the year, it's easy turn it into the result we want:
const str = '12-5 November 17 May 1954';
constMATCH_MONTH_NAME = /\s+([a-z]+)\s+/ifunctionparseDates(input) {
const parts = input.split(MATCH_MONTH_NAME);
const result = { dates: [], year: null };
while (parts.length >= 2) {
const [ days, month ] = parts.splice(0, 2);
result.dates.push({
month,
days: days.split(/\D+/),
});
}
result.year = parts[0];
return result;
}
console.log(parseDates('12-5 November 17 May 1954'));
console.log(parseDates('12 January 1976'));
console.log(parseDates('12 22 March 1965'));
.as-console-wrapper{min-height:100%}
Post a Comment for "How To Check If Numbers Precedes A More "verbal" String?"