manatee manatee - 4 months ago 8
Javascript Question

How do I split the string into an array at an index?

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

Answer

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