Zaki Sediqyar
Zaki Sediqyar

Reputation: 41

JavaScript Regular Expression Rule for repeated characters

I am trying to create a RegEx rule to find side-to-side digits in a number. For example given an array of:

const nums = [1, 2, 33, 4, 22, 5, 66, 112];

I want to remove the digits [33, 22, 66, 112] from the array because they have repeated digits.

I tried the /[0-9/{2} but this seems to not work.

Upvotes: 2

Views: 89

Answers (4)

Code Maniac
Code Maniac

Reputation: 37775

You can use filter with regex pattern ( which uses capturing group and back reference )

  • [0-9]{2} - Means match any digit from 0 to 9 two times which doesn't guaranty repeated digits

  • ([0-9])\1

    • ([0-9]) - Means match digit 0 to 9 ( captured group 1 )
    • \1 - should match the same value as the captured group 1

const nums = [1, 2, 33, 4, 22, 5, 66, 112];

let nonRepeated = nums.filter(num => !/([0-9])\1/.test(""+num)) 

// can replace with !/([0-9])\1/.test(num) because it implicit coerce to string

console.log(nonRepeated)

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386868

the shortest approach is just to check if a same character is followed by itselft. No need for checking dor digits, because the value contains only digits or a dot (or E or space). The last occurs only once.

var nums = [1, 2, 33, 4, 22, 5, 66, 112],
    nonRepeated = nums.filter(v => !/(.)\1/.test(v));

console.log(nonRepeated);

Upvotes: 0

lamnqd
lamnqd

Reputation: 1

You can use filter and includes

const nums = [1, 2, 33, 4, 22, 5, 66, 112];

result = nums.filter(v => ![33, 22, 66, 112].includes(v));

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44145

Use the \1 backreference like so:

/(\d)\1+/

Upvotes: 0

Related Questions