The goal of this was to change the retrieved letters into upper case. I know this works if I stored lines 6 and 7 inside a variable then replace the letters inside the variable called string, but I wanted to know why this code doesn't work instead.
Asked
Active
Viewed 23 times
0
-
1Please post code as [formatted text](/help/formatting), not [a link to a painting of it](https://meta.stackoverflow.com/q/285551/1048572)! – Bergi Jan 27 '23 at 20:30
1 Answers
0
JavaScript strings are not mutable, meaning you can't change the value of a character at a certain index. You'll need to make a new string made of these values.
let string = 'lowercasestring'; // Creates a variable and stores a string.
let letterOne = string.indexOf('l'); // Should store as 0.
let letterTwo = string.indexOf('s'); // Should store as 7.
// mutiple lines for readability
string = string[letterOne].toUpperCase() +
string.slice(letterOne + 1, letterTwo) +
string[letterTwo].toUpperCase() +
string.slice(letterTwo + 1);
console.log(string);
Output:
"LowercaSestring"

Samathingamajig
- 11,839
- 3
- 12
- 34