Skip to content
Advertisement

Why doesn’t this function change the case of the string when it has a similar character like the first letter?

Can’t understand why the following function works for some strings an didn’t work for some which has a similar character like the first.

const change = (str,y) => (str.toLowerCase().replace(str[y],str[y].toUpperCase()));

console.log(change('London',3)); //lonDon
console.log(change('Lagos',3)); //lagOs
console.log(change('Germany',3)); //gerMany
console.log(change('Dcoder',3)); //Dcoder 
console.log(change('Bobby',3)); //Bobby

Advertisement

Answer

The function String.prototype.replace replaces the first occurrence when the first argument is a string.

You can split the string change the index to uppercase and finally join the chars.

const change = (str, y) => {
  const lowercase = str.toLowerCase().split("");
  lowercase[y] = str[y].toUpperCase();
  return lowercase.join("");
};

console.log(change('London',3));
console.log(change('Lagos',3));
console.log(change('Germany',3));
console.log(change('Dcoder',3));
console.log(change('Bobby',3));
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement