Parzh from Ukraine
Parzh from Ukraine

Reputation: 9873

Which RegExp matches a colon between two pairs of digits?

Using .match(), .replace() and other RegExp-things I need to make the RegExp, which could change those example input strings:

'123'
'1234'
'qqxwdx1234sgvs'
'weavrt123adcsd'

to normal output ones:

'1:23'
'12:34'

(So, three-digit clusters must be x:xx formatted).

Upvotes: 0

Views: 693

Answers (1)

Gergo Erdosi
Gergo Erdosi

Reputation: 42043

You can use String.prototype.replace() with a regex that matches 1 or 2 digits followed by 2 digits. $1 is the first captured group (1 or 2 digits), $2 is the second captured group (2 digits). $1:$2 is the replacement, it replaces the matched text with the first captured group ($1) followed by a colon (:), followed by the second captured group ($2).

var string = '123';
string = string.replace(/^(\d{1,2})(\d{2})$/, '$1:$2');

console.log(string); // "1:23"

Explanation of the regex:

  ^                        the beginning of the string
  (                        group and capture to $1:
    \d{1,2}                  digits (0-9) (between 1 and 2 times
                             (matching the most amount possible))
  )                        end of $1
  (                        group and capture to $2:
    \d{2}                    digits (0-9) (2 times)
  )                        end of $2
  $                        before an optional \n, and the end of the
                           string

Upvotes: 2

Related Questions