A string contains only [A-Za-z0-9]
characters. I need to know if the tested string contains at least one repeating character.
The following should return false:
abc1
abc
The following should return true:
abc11
1abc1
aabc1
abca
Use regex with a positive look ahead and capturing group.
/(?=^[A-Za-z0-9]+$)(.)+.*\1.*/
Regex explanation here
Try using this regex for checking whether the characters are unique in the string
var str = 'aabbcc';
var isRepeat = (/([a-zA-Z0-9]).*?\1/).test(str); //Checks for repeated character in string
Can be done with:
^.*?(\w)\1.*?$
See a demo on regex101.com (actually, following matches as well).
If you don't mind that the character class [A-Za-z0-9]
can contain _
as well, \w
is a shortcut for [A-Za-z0-9_]
. Afterwards, the whole expression is bound to the start (^
) and end ($
) of a line/string. Last but not least, the lazy .*?
matches anything before and after, the (\w)\1
at least one repeating character.
If you do mind about the _
, leave it as [A-Za-z0-9]
:
^.*?([A-Za-z0-9])\1.*?$
Thinking about it, I have misread your question. This approach will match words like aabc
or abbc
but not 1abc1
as required in your question. Use a positive lookahead for this as proposed by @Pranav. Although this does not answer the question someone might be interested in this very solution so I tend to leave the answer.
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