Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect repeating letter in an string in Javascript

code for detecting repeating letter in a string.

var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z])\1+$/).test(str)        
alert("repeating string "+hasDuplicates);

I am getting "false" as output for the above string "paraven4sr". But this code works correctly for the strings like "paraaven4sr". i mean if the character repeated consecutively, code gives output as "TRUE". how to rewrite this code so that i ll get output as "TRUE" when the character repeats in a string

like image 849
Pavi Avatar asked Nov 28 '22 11:11

Pavi


2 Answers

JSFIDDLE

var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z]).*?\1/).test(str)        
alert("repeating string "+hasDuplicates);

The regular expression /([a-zA-Z])\1+$/ is looking for:

  • ([a-zA-Z]]) - A letter which it captures in the first group; then
  • \1+ - immediately following it one or more copies of that letter; then
  • $ - the end of the string.

Changing it to /([a-zA-Z]).*?\1/ instead searches for:

  • ([a-zA-Z]) - A letter which it captures in the first group; then
  • .*? - zero or more characters (the ? denotes as few as possible); until
  • \1 - it finds a repeat of the first matched character.

If you have a requirement that the second match must be at the end-of-the-string then you can add $ to the end of the regular expression but from your text description of what you wanted then this did not seem to be necessary.

like image 199
MT0 Avatar answered Dec 01 '22 00:12

MT0


Try this:

var str = "paraven4sr";
function checkDuplicate(str){
    for(var i = 0; i < str.length; i++){
        var re = new RegExp("[^"+ str[i] +"]","g");
        if(str.replace(re, "").length >= 2){
            return true;
        }
    }
    return false;
}
alert(checkDuplicate(str));

Here is jsfiddle

like image 34
Ringo Avatar answered Nov 30 '22 22:11

Ringo