I've still learning javascript so apologies if this is an easy question.
i am trying to replace all occurrences of a word in a string with another word, for example if i am wanting to change all occurrences of the word "brown" with "red" in the following string.
I think the my final output of the variable paragraph when logged to the console should be "The quick red fox jumps over the lazy dog"; however I keep getting "The quick brown fox jumps over the lazy dog";.
I've tried using the splice() method instead of reassigning tempArray to "newWord" in my for loop but it still didn't work. I'm testing in with chrome developer tools.
Here's my code:
/* Creates mechanism that finds a word in a paragraph and replaces it
with another word */
//Declare the original string
var paragraph = "The quick brown fox jumps over the lazy dog";
//Convert paragraph in individual words
var tempArray = paragraph.split(" ");
// Introduce the word to be found; to be replaced
var oldWord = "brown";
// Introduces new word to replace old
var newWord = "red";
//Iterate over the array to find and replace the word
for (var i = 0; i <= tempArray.length; i++) {
if (tempArray[i] === "oldWord") {
tempArray[i] = "newWord";
}
}
/* Reconvert the modified array to string by assigning it to the
original variable */
paragraph = tempArray.join(" ");
// Display your results, it's not an array anymore
console.log(paragraph);