This code will not work as expected. JavaScript strings are immutable, meaning that their values cannot be modified once they are created. So when you try to change the value of a character in the string using the code phrase[i] = '*', it will throw an error.
Here is a possible way to write the function using split(), join(), and map() methods
function changingLetters(phrase, letter) {
return phrase.split('').map(char => char === letter ? '*' : char).join('');
}
console.log(changingLetters('This is a test','s'));
This code will split the string into an array of individual characters, then it will iterate over that array and use the map function to return a new array with the character replaced by '*' if the original character is the same as the letter you passed. and then join back the array of characters to form a string again.
You can also use replace() method
function changingLetters(phrase, letter) {
return phrase.replace(new RegExp(letter,'gi'),'*');
}
console.log(changingLetters('This is a test','s'));
the replace(new RegExp(letter,'gi'),'') will replace all occurences of letter with '', 'gi' makes the replace operation case-insensitive and global, i.e it will replace all occurence of letter regardless of the case and will match all occurences not just the first one.