Alessandro
Alessandro

Reputation: 519

parsing time string jQuery

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.

Upvotes: 1

Views: 1415

Answers (2)

adeneo
adeneo

Reputation: 318222

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

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626920

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)

Upvotes: 2

Related Questions