I need to split this string 3:00pm so it ends up as [3:00][pm]. Below is my attempt but it is not correct because the console prints p m.
date = '3:00pm'
var elem = date.slice(date.length-2);
5 Answers 5
You can get the two different parts with two different slices.
var date = '3:00pm';
var arr = [
date.slice(0, -2), // first to 2nd from last
date.slice(-2) // just the last 2
];
console.log(arr);
answered Jul 11, 2016 at 20:48
Mike Cluck
32.6k13 gold badges84 silver badges95 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can use String.prototype.match() with RegExp /\d+:\d+|\w+/g
var date = "3:00pm"
var elem = date.match(/\d+:\d+|\w+/g);
console.log(elem[0], elem[1])
Comments
You could use a regex with positive lookahead.
console.log("3:00pm".split(/(?=[ap]m)/));
console.log("11:55am".split(/(?=[ap]m)/));
answered Jul 11, 2016 at 20:56
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
4 Comments
Morteza Tourani
Maybe need to check
am tooMorteza Tourani
That looks great. but may I know why regex and not a simple substring?
Nina Scholz
@mortezaT, just for fun.
Morteza Tourani
That's a good point. I've tried that and I think works perfect most of the time.
var date = '3:00pm';
var time = date.substr(0, date.length - 2); // 3:00
var period = date.substr(date.length - 2); // pm
console.log(time);
console.log(period);
answered Jul 11, 2016 at 20:49
TimoStaudinger
42.7k16 gold badges91 silver badges96 bronze badges
1 Comment
depperm
I'd change the 4 in both spots to
date.length-2 or -2 so that 10, 11, and 12 would also work, and remove the 2 in the period lineI believe you want to split not only 3:00pm but also other times. Here is a sample using Regular Expression.
var re=/([0-9:]+)\s*(am|pm)/i;
var ar=[];
'3:00pm'.replace(re,function(m/*whole match ([0-9:]+)\s*(am|pm)*/, pt1/*([0-9:]+)*/, pt2/*(am|pm)*/){
ar.push(pt1, pt2); //push captures
return m; //do not change the string
});
console.log(ar); //["3:00","pm"]
answered Jul 11, 2016 at 21:00
Alex Kudryashev
9,5103 gold badges31 silver badges39 bronze badges
Comments
lang-js
.slice()returns a string, not an array. You probably want to use.split()here.