Home > Net >  Function Declaration that removes keywords stored in an array from a string
Function Declaration that removes keywords stored in an array from a string

Time:02-01

I have a function declaration that I need to use. Its purpose is to remove various keywords (that should not have been in the string) contained in an array from a string contained in the console.log.

This will make the string readable. Please Help, I'm currently learning.

By removing "not", "hello" from the string, this will give "If string includes words in array, remove them JavaScript".

function correctString(string, Keywords) {
    let spec1 = Keywords;
    let spec2 = spec1.pop();
    return string.replace(spec2, "");
}

console.log(correctString("If stringnot includes whelloords in array, remove them JavaScript", ["not", "hello"]));

I was able to remove the "hello" keyword from the string with the pop method. However, I cannot find a method that removes the other keyword "not" from the string... I tried to use different methods such as .filter, .splice, .slice.

CodePudding user response:

Is this what you're trying to accomplish? See this MDN document and especially the statement in the first paragraph that "The original string is left unchanged." You may also be interested in replaceAll().

function correctString(text, Keywords) {
    Keywords.forEach( v => {
      console.log(v   ": "   text.indexOf(v));
      text = text.replace(v,"");
      console.log(text);
      });
    return text;
}


console.log(correctString("If stringnot includes whelloords in array, remove them JavaScript", ["not", "hello"]));

  • Related