Regular expression for line splitting, but seperator capture

I have a string say "dd month yyyy" and I want split to convert to an array, for example ["dd", "," month ",", "yyyy"].

What I still have and this method works. But am I looking for a Reg expression if someone can help?

function toArray(format) { var vDateStr = ''; var vComponantStr = ''; var vCurrChar = ''; var vSeparators = new RegExp('[\/\\ -.,\'":]'); var vDateFormatArray = new Array(); for (var i=0; i < pFormatStr.length; i++ ) { vCurrChar = pFormatStr.charAt(i); if ( (vCurrChar.match(vSeparators) ) || (i + 1 == pFormatStr.length) ) // separator or end of string { if ( (i + 1 == pFormatStr.length) && ( !(vCurrChar.match(vSeparators) ) ) ) // at end of string add any non-separator chars to the current component { vComponantStr += vCurrChar; } vDateFormatArray.push( vComponantStr ); if ( vCurrChar.match(vSeparators) ) vDateFormatArray.push( vCurrChar ); vComponantStr = ''; } else { vComponantStr += vCurrChar; } } return vDateFormatArray; } 
+6
source share
3 answers

Plain:

 > "10 Jan 2015".split(/\b/g) < ["10", " ", "Jan", " ", "2015"] 

This will split at the word boundary.

+5
source

I assume that "mm dd yyyy" will actually be a number, but this will also work for strings.

 var date ="01 02 1292"; var dateArr = date.match(/[^\s]+|\s/g); document.write(JSON.stringify(dateArr)); 
+3
source

 function toArray(format) { var r = new RegExp('([0-9]{2})( )([0-9]{2})( )([0-9]{4})'); return format.match(r).slice(1); } document.write(JSON.stringify(toArray("30 12 1980"))); 
+1
source

Source: https://habr.com/ru/post/986318/


All Articles