Here i have a time which is in the format of hh:mma . AM/PM are not separated using white space with time.Now how to use regex to get the AM/pm and the time using javascript.
Asked
Active
Viewed 670 times
-1
-
Do you have a string containing just that time format or the string contain more stuff? – Claudio Redi Apr 30 '14 at 12:13
-
1possible duplicate of [Regex for AM PM time format for jquery](http://stackoverflow.com/questions/8820372/regex-for-am-pm-time-format-for-jquery), which doesn't use jQuery. – Patrick Hofman Apr 30 '14 at 12:15
-
string contains only time format "12:30AM" without space between time and AM/PM. how to get hours, minutes , am/pm USING REGEX – user13763 Apr 30 '14 at 12:17
1 Answers
3
You don't need a regex to "get" the values:
var time = "12:30PM",
suffix = time.substr(-2),
numbers = time.substr(0, time.length-2);
Results:
console.log(suffix); // "PM"
console.log(numbers); // "12:30"
If you want the hours / minutes in separate variables:
var temp = numbers.split(':'),
hours = parseInt(temp[0], 10), // 12
minutes = parseInt(temp[1], 10); // 30

Cerbrus
- 70,800
- 18
- 132
- 147
-
-
-
_"give it fully"_? `10` is the radix parameter for [`parseInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Parameters), this makes sure that the first parameter is interpreted as a decimal number. – Cerbrus Apr 30 '14 at 12:21
-
No, `.substr(-2)` returns the last 2 character from that string. In this case, `"PM"`; – Cerbrus Apr 30 '14 at 12:26
-
-
A little, indeed. But did you get the desired results out of my answer? – Cerbrus Apr 30 '14 at 12:31