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

时间:2016-07-11 20:45:27

标签: javascript

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 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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])

答案 2 :(得分:1)

You could use a regex with positive lookahead.

console.log("3:00pm".split(/(?=[ap]m)/));
console.log("11:55am".split(/(?=[ap]m)/));

答案 3 :(得分: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);

答案 4 :(得分: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"]