1

I have a function which parses time strings, formatted as hh:mm (for example 18:45). Hours and minutes can be divided by colon, a blank space (18 45) or a comma (18,45).

The following variables split the time string if a colon is used:

var hourstart = parseInt(ini.substr(0, ini.indexOf(':')));
var minutestart = parseInt(ini.substr(ini.indexOf(":") + 1));

How can I make them work also when a blank space or a comma is used? I tried with:

ini.indexOf(':'||' '||',')

but it does not work.

2 Answers 2

2

If you want to also check if the string conforms to the format digits+, .+digits, you may use a /^(\d+)[ :,](\d+)$/ regex (or even /^(0?[0-9]|1[0-9]|2[0-3]):([0-5][0-9])$/):

var s = "18:45";
var m = s.match(/^(\d+)[ :,](\d+)$/);
if (m) {
  console.log("Hour: " + parseInt(m[1]));
  console.log("Minute: " + parseInt(m[2]));
}

Details:

  • ^ - start of string
  • (\d+) - Group 1 (hours) capturing 1 or more digits
  • [ :,] - a character class matching 1 single char: either a space, or : or ,
  • (\d+) - Group 2 (minutes) capturing 1 or more digits
  • $ - end of string.

AND

  • (0?[0-9]|1[0-9]|2[0-3]) - captures hours from 00 to 23 with an optional leading 0 and
  • ([0-5][0-9]) - captures minutes (from 00 to 59)
Sign up to request clarification or add additional context in comments.

2 Comments

Might want \d{1,2} / \d{2} rather than \d+. Not clear from the question if 1am is 1:00 or 01:00
Well, following that path, it can even be /^(0?[0-9]|1[0-9]|2[0-3]):([0-5][0-9])$/. That depends on the level of the input string "pre-validation".
2

You can use a regex to split with

var time  = "18 45";

var parts = time.split(/[,\s\.\:]+/).map(Number);

var hours = parts.shift();
var mins  = parts.shift();

console.log(hours);
console.log(mins);

5 Comments

I added the colon char. It works. var parts = ini.split(/[:,\s\.]+/).map(Number); var hourstart = parseInt(parts.shift()); var minutestart = parseInt(parts.shift());
Forgot the colon, added it now. You don't have to parse the values, they are already integers, that's what the .map(Number) part does, it parses all the values as numbers.
Without parseInt it returned NaN:NaN value, after some computations on the hour/minute values.
@Alex - your code probably did, this does not, as there's nothing to parseInt, it's already numbers.
Sure adeneo. The issue was on my side. Thanks for your explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.