0

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);
TheThirdMan
  • 1,482
  • 1
  • 14
  • 27

2 Answers2

0

you can use replace() function try something like:

var result="";
var para="hello hello test word ";
result=para.replace("hello","replaced");
console.log(para);//original values
console.log(result);//modified one
RohitS
  • 1,036
  • 12
  • 17
0

As pointed out in the comments, the best solution to this problem might be using replace.

However (and for learning purposes), your code works fine if you make a couple of changes in the for statement and the loop body:

for (var i = 0; i < tempArray.length; i++) {// You have to iterate until tempArray.length - 1
    if (tempArray[i] === oldWord) {// Don't wrap it in ""
        tempArray[i] = newWord;// Don't wrap it in ""
    }
}

I will elaborate the comments I put in the code a bit more:

  1. In js, strings are wrapped in double quotes or simple quotes. If you wrap the name of a variable in quotes, JS will treat it as a string and not as a variable. Thus the comparation won't be correct.
  2. In an array, valid indexes are from 0 to array.length - 1. Accesing an array in position array.length will not throw an error (as in other languages, like Java) but it will return undefined (which usually isn't the expected behaviour).

You can check the result of your code in this fiddle (opening the console). Hope it helps.

Community
  • 1
  • 1
acontell
  • 6,792
  • 1
  • 19
  • 32