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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With