Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To check if a letter is repeated in a string in javascript, use the test() method with /(.).*\1/ regex it is the simplest way to check string has a duplicate characters or not.

Today, I’m going to show you How do I check if a letter is repeated in a string in javascript, as mentioned above, I’m going to create a function that checks string contains a duplicate character or not.

Let’s start today’s tutorial on how do you check if a letter is repeated in a string in javascript.

Javascript checks if a letter is repeated in a string

Here, we will do

  1. Create a function which checks duplicate letter
  2. Use the test() method with regex in a function to check repeated letter
  3. Check the function in sample strings
// Create a function which checks duplicate letter
function hasRepeats(str) {

    // Use `test()` method with regex in a function to check repeated letter
    return /(.).*\1/.test(str);
}

// Check function in sample strings

function hasRepeats (str) {
    return /(.).*\1/.test(str);
}

console.log(hasRepeats("infinitbility.com"))    // true

console.log(hasRepeats("aguidehub.com"))        // true

console.log(hasRepeats("sortoutcode.com"))      // true

console.log(hasRepeats("abcdefg"))              // false

Output

I hope it helps you, All the best đź‘Ť.