4

I need to create a validation that determines if a string is only made of repeated chars. So, for example it would catch "pp" but not "happy".

So far, I can check for the repeating char using this:

/(.)\1+/.test(value);

How can I change this regex to only catch "pp" and not catch "happy"? Would regex be the best way to do this?

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Nora
  • 53
  • 4

2 Answers2

6

Your regex is almost valid, you only have to add ^ and $ respectively at the beginning and at the end, to ensure that the string doesn't contain any other characters:

/^(.)\1+$/.test(value);

See also a Regex101 demo.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
1

An inverse should also work.. ie, this regex should match a string which contain two non repeated characters or empty string. Negation ! exists before the regex should do an inverse match.

> !/(.)(?!\1).|^$/.test('happy')
false
> !/(.)(?!\1).|^$/.test('')
false
> !/(.)(?!\1).|^$/.test('pp')
true
> !/(.)(?!\1).|^$/.test('ppo')
false
> !/(.)(?!\1).|^$/.test('ppppppppp')
true
> 

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • You are essentially saying, return true if it not the case that there is some subsequent character different than the first one. In what ways is this better than a regexp which just says return true if all the subsequent characters are the same? –  Feb 07 '16 at 05:43