简体   繁体   中英

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

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 .

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"]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM