1

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?

asked Oct 1, 2013 at 14:46
2
  • what was your intention in adding [a-z] characters to the regex? Do you expect to get alphanumeric values? Commented Oct 1, 2013 at 14:53
  • Users never can be to... you get it.. Commented Oct 1, 2013 at 14:59

3 Answers 3

3

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)
answered Oct 1, 2013 at 14:53
Sign up to request clarification or add additional context in comments.

Comments

1

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

answered Oct 1, 2013 at 14:52

Comments

0

try substring

 String str="20130820";
 String year=str.subString(0,3);
 String month=str.subString(4,5);
 String date=Str.subString(6,7);
answered Oct 1, 2013 at 14:52

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.