Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a sting which contains a date, but date object wont accept it, so i have to make it into a valid format.

I tried this

"20130820".split(/^[a-z0-9]{4}[a-z]{2}[a-z0-9]{2}?$/) 

It should give out an array like

["2013", "08", "20"]

Any idea where i am wrong?

share|improve this question
    
what was your intention in adding [a-z] characters to the regex? Do you expect to get alphanumeric values? –  devnull69 Oct 1 '13 at 14:53
    
Users never can be to... you get it.. –  Sangoku Oct 1 '13 at 14:59

3 Answers 3

up vote 3 down vote accepted

You want to use .match rather than .split. You need to capture each group, and the second character class is also a-z when it should probably just be \d.

"20130820".match(/^(\d{4})(\d{2})(\d{2})$/).slice(1)
share|improve this answer

Why split, you can use String#match:

var m = "20130820".match(/^(\d{4})(\d{2})(\d{2})$/);
//=> ["20130820", "2013", "08", "20"]

btw for this simple job you don't need regex just use String#substring

share|improve this answer

try substring

   String str="20130820";
   String  year=str.subString(0,3);
   String  month=str.subString(4,5);
   String  date=Str.subString(6,7);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.