Detect repeating letter in an string in Javascript

前端 未结 4 1793
长发绾君心
长发绾君心 2021-01-06 19:18

code for detecting repeating letter in a string.

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


        
相关标签:
4条回答
  • 2021-01-06 19:31

    Something like this?

    String.prototype.count=function(s1) { 
       return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
    }
    
    "aab".count("a") > 1
    

    EDIT: Sorry, just read that you are not searching for a function to find whether a letter is found more than once but to find whether a letter is a duplicate. Anyway, I leave this function here, maybe it can help. Sorry ;)

    0 讨论(0)
  • 2021-01-06 19:33

    To just test duplicate alphanumeric character (including underscore _):

    console.log(/(\w)\1+/.test('aab'));
    
    0 讨论(0)
  • 2021-01-06 19:38

    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

    0 讨论(0)
  • 2021-01-06 19:43

    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.

    0 讨论(0)
提交回复
热议问题