Checking if a string contains all unique characters using JavaScript



Problem

We are required to write a JavaScript function that takes in a sting and returns true if all the characters in the string appear only once and false otherwise.

Example

Following is the code −

 Live Demo

const str = 'thisconaluqe';
const allUnique = (str = '') => {
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(str.indexOf(el) !== str.lastIndexOf(el)){
         return false;
      };
   };
   return true;
};
console.log(allUnique(str));

Output

true

Advertisements