A regular expression for a string made of only repeated characters

I need to create a validation that determines whether a string will be made only of duplicate characters. So, for example, he would catch "pp", but not "satisfied."

So far, I can check the repetition of char with this:

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

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

+4
source share
2 answers

Your regular expression is almost valid, you only need to add ^both $at the beginning and at the end, to make sure that the line does not contain other characters:

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

. Regex101.

+6

. .. , . ! , .

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

DEMO

+1

Source: https://habr.com/ru/post/1627617/


All Articles