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.
JavaScript
x
7
1
const change = (str,y) => (str.toLowerCase().replace(str[y],str[y].toUpperCase()));
2
3
console.log(change('London',3)); //lonDon
4
console.log(change('Lagos',3)); //lagOs
5
console.log(change('Germany',3)); //gerMany
6
console.log(change('Dcoder',3)); //Dcoder
7
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.
JavaScript
1
11
11
1
const change = (str, y) => {
2
const lowercase = str.toLowerCase().split("");
3
lowercase[y] = str[y].toUpperCase();
4
return lowercase.join("");
5
};
6
7
console.log(change('London',3));
8
console.log(change('Lagos',3));
9
console.log(change('Germany',3));
10
console.log(change('Dcoder',3));
11
console.log(change('Bobby',3));