[Solved] Why is my string getting repeatedly in this function?


  • Your for(var j=0; j < accentArray.length; j++) is meaningless. You
    are not using the j variable anywhere. You just make the inner
    codes run accentArray.length times. If you want to check if the
    string includes an accent, you could write

    if ([...str].some(c => accentArray.includes(c)))

  • There is a better way to remove characters from a string: use
    String.replace()

  • String is a built-in class name. Avoid using it as
    your own variable name.

  • if(str.length <= 4){}else(str.length >=4){} is equivalent to if(str.length <= 4){}else{}

  • if..else.. statement which simply returns/sets a value in the body can be simplified with ternary operator.

var accentArray = ["á", "à", "ã", "â", "é", "è", "ê", "í", "ì", "î", "õ", "ó", "ò", "ô", "ú", "ù", "û"]

function encrypt(str)
{
  return (str.length <= 4) ? str.replace(/[aeiou]/g,"") :
        [...str].some(c => accentArray.includes(c)) ? str.replace(/n/g,"") : "";
    
}
console.log(encrypt('atención'));
console.log(encrypt('aten'));

solved Why is my string getting repeatedly in this function?