manatee
manatee

Reputation: 185

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

Upvotes: 0

Views: 69

Answers (5)

Nina Scholz
Nina Scholz

Reputation: 386868

You could use a regex with positive lookahead.

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

Upvotes: 1

Alex Kudryashev
Alex Kudryashev

Reputation: 9480

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

Upvotes: 0

guest271314
guest271314

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

Upvotes: 1

TimoStaudinger
TimoStaudinger

Reputation: 42530

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

Upvotes: 0

Mike Cluck
Mike Cluck

Reputation: 32531

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

Upvotes: 5

Related Questions