0

I want to see if the string I have is in the form of HH:MM:SS.

Here is what I have so far:

d = '00:01:01'
d.match(/\d{2}:\d{2}:\d{2}/)
["00:01:02"]

Is there a way to just get a True/False, instead of an array?

David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

1

Use .test method of Regexp object.

/\d{2}:\d{2}:\d{2}/.test(d)
// true
Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
0

Perhaps, you can use regex.test(str) but it's also possible using match because on success, match returns an array which is a truthy value and on failure, match returns null which is a falsy value. Check this to understand truthy and falsy.

So, if you use

if(d.match(/\d{2}:\d{2}:\d{2}/)) {
    // true
}
else {
    // false
}

This will work, check this fiddle as an example and this answer as well (about !!), I've used !! in my example, so you may have doubts.

Community
  • 1
  • 1
The Alpha
  • 143,660
  • 29
  • 287
  • 307