Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to split the string but capture sperator

I have string say "dd month yyyy" and I want split to convert to array like ["dd", " ", "month", " ", "yyyy"].

What I have so far and this method works. But I'm looking for Reg expression to do 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;
}
like image 516
Reddy Avatar asked Apr 30 '15 17:04

Reddy


2 Answers

Simple:

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

This will split on a word boundary.

like image 124
James Wilkins Avatar answered Sep 19 '22 01:09

James Wilkins


I assume that "mm dd yyyy" will actually be numbers, but this will work for the strings as well.

var date ="01 02 1292";

var dateArr = date.match(/[^\s]+|\s/g);

document.write(JSON.stringify(dateArr));
like image 22
KJ Price Avatar answered Sep 19 '22 01:09

KJ Price