0

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);
asked Jul 11, 2016 at 20:45
1
  • 1
    .slice() returns a string, not an array. You probably want to use .split() here. Commented Jul 11, 2016 at 20:47

5 Answers 5

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
Sign up to request clarification or add additional context in comments.

Comments

1

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])

answered Jul 11, 2016 at 20:53

Comments

1

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

4 Comments

Maybe need to check am too
That looks great. but may I know why regex and not a simple substring?
@mortezaT, just for fun.
That's a good point. I've tried that and I think works perfect most of the time.
0

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

1 Comment

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 line
0

I 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

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.