Raj
Raj

Reputation: 193

To add space before AM/PM

I have a string like "06:35PM". I want to add a space before AM/PM, resulting in "06:35 PM".

var timeValue = "06:35PM";
var hours = Number(timeValue.match(/^(\d+)/)[1]);
var minutes = Number(timeValue.match(/:(\d+)/)[1]);
var AMPM = timeValue.match(/\s(.*)$/)[1];
travelInfo.PreCruise[field] = hours + ":" + minutes + " " + AMPM;

But at the 4th line, I get this error: Cannot read property '1' of null.

How can I write a regular expression to do this?

Upvotes: 1

Views: 2111

Answers (6)

Niklesh Raut
Niklesh Raut

Reputation: 34914

Replace s with Sas s Find a whitespace character which you don't have,

var AMPM = timeValue.match(/\S(.*)$/)[1];

Upvotes: 1

user5633496
user5633496

Reputation:

Try this Regular expression.

/\S(.*)$/

Hope it helps.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074535

Just do a single replace without parsing the numbers:

timeValue = timeValue.replace(/[AP]/, " $&");

var timeValue = "06:35PM";
timeValue = timeValue.replace(/[AP]/, " $&");
console.log(timeValue);

The regex [AP] matches an A or a P. The replacement string has the space you want, and $& which means "insert whatever matched here," meaning that $& will take the value A if it was an A that matched, or P if it was a P that matched.

Upvotes: 2

brk
brk

Reputation: 50316

You can do like this

var timeValue = "06:35PM";
// get the last two characters
var last2 = timeValue.slice(-2);
// Create a substring removing the last two characters
var x = timeValue.substr(0, timeValue.length-2)
// concat them adding a space in between
var t = x+' '+last2
console.log(t)

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

Or maybe something as simple as adding space before last two alphabets

Demo

var timeValue = "06:35PM";
console.log( timeValue.split(/(?=[A-Z]{2})/).join(" ") );

Upvotes: 0

Om Sao
Om Sao

Reputation: 7653

How about?:

str.replace("A", " A").replace("P", " P");

Upvotes: 2

Related Questions