Reputation: 193
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
Reputation: 34914
Replace s
with S
as s
Find a whitespace character which you don't have,
var AMPM = timeValue.match(/\S(.*)$/)[1];
Upvotes: 1
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
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
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