Carson
Carson

Reputation: 194

Filter not filtering from Regex

I am having having some trouble with a filter function that does not want to do what I need it to do.

I need this array to be filtered for strings within it that contain consecutive repeats of the same letter.

This is what I have:

var regex = /(.)\1+/g;

var filtered = permutations.filter(function(string){
    return !string.match(regex);
  });

Where permutations is equal to ["a,a,b", "a,a,b", "b,a,a", "a,b,a", "a,b,a", "b,a,a"]

The output for this just shows the same: ["a,a,b", "a,a,b", "b,a,a", "a,b,a", "a,b,a", "b,a,a"]

The output should be:

["a,b,a","a,b,a"]

Any idea what I am doing wrong?

Upvotes: 2

Views: 1992

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

It seems you need to match a repeated char after a comma, thus, change your pattern to

/(.),\1/

See the regex demo

Details:

  • (.) - Capturing group matching a single char other than a line break char
  • , - a comma
  • \1 - backreference to capture group 1.

var regex = /(.),\1/;
var permutations = ["a,a,b", "a,a,b", "b,a,a", "a,b,a", "a,b,a", "b,a,a"];
var filtered = permutations.filter(function(string){
   return !regex.test(string);
});
console.log(filtered);

Upvotes: 3

Related Questions