Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for repeated characters in a string Javascript

Tags:

I was wondering if there is a way to check for repeated characters in a string without using double loop. Can this be done with recursion?

An example of the code using double loop (return true or false based on if there are repeated characters in a string):

var charRepeats = function(str) {     for(var i = 0; i <= str.length; i++) {         for(var j = i+1; j <= str.length; j++) {             if(str[j] == str[i]) {                 return false;             }         }     }     return true; } 

Many thanks in advance!

like image 843
yinjia Avatar asked Nov 11 '15 17:11

yinjia


People also ask

How do you check if a character is repeated in a string JavaScript?

The function should detect if the string is a repetition of a same set of characters or not. If it is a repetition of the same set of characters then we should return true, false otherwise. const output = true; because the string 'car' is getting repeated over and over again in the string.


2 Answers

(A recursive solution can be found at the end, of this answer.)

You could use the builtin javascript Array functions some MDN some reference

 var text = "test".split("");  text.some(function(v,i,a){    return a.lastIndexOf(v)!=i;  }); 

callback parameters:
v ... current value of the iteration
i ... current index of the iteration
a ... current array

.split("") create an array from a string
.some(function(v,i,a){ ... }) goes through an array until the function returns true, and ends than right away. (doesn't loop through the whole array, if it finds an match earlier)

Details to the some function can be found here

Tests, with several different strings:

var texts = ["test", "rest", "why", "puss"];  for(var idx in texts){     var text = texts[idx].split("");     document.write(text + " -> " + text.some(function(v,i,a){return a.lastIndexOf(v)!=i;}) +"<br/>");        }   //tested on win7 in chrome 46+

If recursion is needed.

Update for recursion:

//recursive function function checkString(text,index){     if((text.length - index)==0 ){ //stop condition         return false;      }else{         return checkString(text,index + 1)          || text.substr(0, index).indexOf(text[index])!=-1;     } }  // example Data to test var texts = ["test", "rest", "why", "puss"];  for(var idx in texts){     var txt = texts[idx];     document.write( txt +  " ->" + checkString(txt,0) + "<br/>"); } //tested on win7 in chrome 46+
like image 174
winner_joiner Avatar answered Oct 27 '22 23:10

winner_joiner


This will do:

function isIsogram (str) {     return !/(.).*\1/.test(str); } 
like image 35
thedarklord47 Avatar answered Oct 27 '22 23:10

thedarklord47