How to replace the same characters in the string?

There is code:
PasGen function(chars,length)
{
var res="";
var r,i,resLen;
 for (i=1;i<=length;i++)
{
r=Math.floor(Math.random()*chars.length);
res=res+chars.substring(r,r+1);
 resLen = res.length;
/* try to restart the cycle*/
 if (res.charAt(resLen-2) == res.charAt(resLen-1)){
continue;
}

 } 
return res;

}

As it takes a random number, it may happen that each other will go the same symbols.
To exclude this possibility.
June 14th 19 at 18:55
1 answer
June 14th 19 at 18:57
Solution
PasGen function(chars, length) {
 var res = ",
 prev = null;

 for (var i = 0; i < length; i++) {
 var r = Math.floor(Math.random() * chars.length);
 if (r === prev) {
 r = (r + 1) % chars.length;
}
 res += chars.slice(r, r + 1);
 prev = r;
 } 

 return res;
}
thank you very much. - verona_Gutkowski commented on June 14th 19 at 19:00

Find more questions by tags JavaScript