Double Characters in Regular Expressions

5

I am training my javascript and am wondering how I look for repeated characters in a regular expression

Example: I type aa in a textbox and, within a validation method, the method checks whether the character a, typed twice in a row, is inside RegExp

    
asked by anonymous 11.05.2017 / 20:03

1 answer

3

What you want to do would need something called backreference ( link ) where a previously captured group is referenced within the regular expression. It would look like this:

(.)

That is:

  • (.) Match any character and create a group
  • Find the character you just found again

You can mix this with + or {min,max} repeat ranges to make any match:

(.){2,4}
  • (.) Same as above
  • {2,4} Match 3 to 5 repeated characters

Or:

(.){2}
  • (.) Same as above
  • {2} Match exactly 2 repeated characters

Or:

(.)+
  • (.) Same as above
  • + Match 2 or more repeated characters

If you want to be more specific (you are only looking for repetitions of space type characters, for example), just change the group (.) to what you would like repeated.

In code:

function hasRepetition(str) {
  return /(.)/.test(str);
}

hasRepetition('best') // false
hasRepetition('beest') // true
    
11.05.2017 / 20:14