Norman
Norman

Reputation: 6365

Javascript get first and next two digits of a number

How can I get the first and next to digits of a number as an array using regex in JavaScript?

I was doing this :

let foo = '1234567'; 

let op = foo.match(/^\d{1}|\d{2}/g)

console.log(op)

But this outputs everything even after the third number.

Im trying to get the output as

[1,23]

Upvotes: 4

Views: 376

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You may capture the first and the next two digits into separate captuirng groups:

let foo = '1234567'; 
let op = foo.match(/^(\d)(\d{2})/);
if (op) {
  console.log(op.slice(1));
}

Here,

  • ^ - matches the start of string
  • (\d) - captures a digit into Group 1
  • (\d{2}) - captures the second and third digit into Group 2.

See the regex demo.

Before accessing group values, you should check if there was a match, hence, you might use a check like if (op) {...}. .slice(1) is used to get rid of the first value in the array, which is always the whole match value.

If you need to use your regex with alternation and g modifier for some reason, you can only make it work with a lookbehind that is now available in the majority of JavaScript environments:

console.log( '1234567'.match(/^\d|(?<=^\d)\d{2}/g) );

Here,

  • ^\d - matches the digit at the start of string
  • | - or
  • (?<=^\d)\d{2} - two digits that are preceded with a digit at the start of string.

See this regex demo.

Upvotes: 5

Amacado
Amacado

Reputation: 617

let foo = '1234567'; // input string
let op = foo.match(/^(\d)(\d{2})/); // regex
let opSliced = op.slice(1); // slice 
console.log(opSliced);

Upvotes: 1

Related Questions