-3

I have made a function which is used to delete a certain word from a variable i also made.

var eliminateWord = function (usedwords){word2.replace (/go/g," ");

but i cant seem to use the function in this code:

var word1 = "go",

word2 = "go to the shops everyday and buy chocolate.";

var eliminateWord = function (usedwords){
word2.replace (/go/g," ");
};

if (word2.match("go")) {
    console.log("user entered go");
    eliminateWord ();
}
if (word2.match("to")) {
    console.log("user entered to");
}

if (word2.match("the")) {
    console.log("user entered the");
}
if (word2.match("and")) {

    console.log("user entered and");
}
console.log(word2);

2 Answers2

1

The replace method returns the modified string. It doesn't modify the string in place (and couldn't anyway, since strings are immutable). Since you aren't doing anything with the return value in the function, the changed string is discarded.

You are also messing about with globals, which is a good way to write confusing code. Pass arguments instead.

Also, there doesn't seem to be any reason to use a function expression instead of a function declaration here.

function eliminateWord(word){
    return word.replace(/go/g," ");
}

word2 = eliminateWord(word2);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

Just return the value obtained with replace:

var eliminateWord = function (usedwords){return word2.replace (/go/g," ");
ilovebigmacs
  • 983
  • 16
  • 28