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
Sangoku
1,6262 gold badges23 silver badges52 bronze badges
-
what was your intention in adding [a-z] characters to the regex? Do you expect to get alphanumeric values?devnull69– devnull692013年10月01日 14:53:41 +00:00Commented Oct 1, 2013 at 14:53
-
Users never can be to... you get it..Sangoku– Sangoku2013年10月01日 14:59:06 +00:00Commented Oct 1, 2013 at 14:59
3 Answers 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
Explosion Pills
192k56 gold badges341 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
anubhava
791k67 gold badges604 silver badges671 bronze badges
Comments
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
Rijo Joseph
1,4053 gold badges18 silver badges35 bronze badges
Comments
lang-js