sensei
sensei

Reputation: 7562

Regex exclude exact digit from digits

Hello my fellow dream builders.

I am parsing time from twitter and I am using this regex:

    {

        match = /^[1]/.exec(obj.tweetTime);
        if(match != null){
            time = "1 hour ago";
        }
        else
        {
        match = /^[0-9]{1,2}/.exec(obj.tweetTime);
        time = match + " hours ago";
        }
    }

My question is, if there is simpler way to do this? As you can see, I have 2 digits for time. I just want to format my print right. Hour/Hours as you can see.

Is it possible to write only 1 regex and use only 1 conditional bracket?

PS: I am beginner at regex, and I know /^[0-9]{1,2}/ allow numbers from 0 to 99 practically, but as I said it works for my needs, just asking if it is possible to do this properly, since I lack knowledge.

Thank you, much love <3

Upvotes: 0

Views: 524

Answers (1)

Xophmeister
Xophmeister

Reputation: 9211

I would do it like this:

var match = obj.tweetTime.match(/^\d+$/);

if (match) {
  var time = match[0] + ' hour' + (match[0] == 1 ? '' : 's') + ' ago';
}

EDIT Turns out the string is formatted! In which case:

var match = obj.tweetTime.match(/^(\d+)([smhd])$/);

if (match) {
  var units = { s: 'second', m: 'minute', h: 'hour', d: 'day' },
      time  = match[1] + ' ' + units[match[2]] + (match[1] == 1 ? '' : 's') + ' ago';
}

To explain the regex:

^         Anchor matches to the beginning of the string
(\d+)     Capture one or more digits in first group
([smhd])  Capture s, m, h or d in second group
$         Anchor to end of string

Upvotes: 1

Related Questions