如何在javascript中从字符串中删除单词数组?

如何在javascript中从字符串中删除单词数组?,javascript,arrays,Javascript,Arrays,我有一个函数可以从字符串中删除单词。它是: var removeFromString = function(oldStr, fullStr) { return fullStr.split(oldStr).join(''); }; 我是这样使用它的: console.log( removeFromString("Hello", "Hello World") ); // World console.log( removeFromString("Hello", "Hello-

我有一个函数可以从字符串中删除单词。它是:

  var removeFromString = function(oldStr, fullStr) { 
    return fullStr.split(oldStr).join(''); 
  };
我是这样使用它的:

 console.log( removeFromString("Hello", "Hello World") ); // World
 console.log( removeFromString("Hello", "Hello-World") ); // -World
 var c = removeFromString(["one, two," , "and four"], str); // Remove not three
 console.log(c); // Remove not three
但主要问题是:

 var str = "Remove one, two, not three and four"; 
在这里,我们必须删除一个,两个和四个。这可以通过以下方式实现:

var a = removeFromString("one, two,", str); // Remove not three and four
var b = removeFromString("and four", a); // Remove not three
console.log(b); // Remove not three
在上面的示例中,我必须使用该函数两次。我希望它是这样的:

 console.log( removeFromString("Hello", "Hello World") ); // World
 console.log( removeFromString("Hello", "Hello-World") ); // -World
 var c = removeFromString(["one, two," , "and four"], str); // Remove not three
 console.log(c); // Remove not three
是的,我实际上想升级removeFromString函数!我如何才能做到这一点?

您可以使用join并从数组中动态生成regex,并替换匹配的值

wordArray.forEach(word => {
    sentence = sentence.replace(word, '');
})
函数removeFromStringarr,str{ 让regex=newregexp\\b+arr.join'|'+\\b,gi 返回str.replaceregex, } logremoveFromString[1,2和4],删除1,2,而不是3和4; logremoveFromString[one,and four],删除one,two,而不是three和four;
console.logremoveFromString[Hello],Hello World您需要这样的东西:

function newRemoveFromString(stringArray,string){

    for(var i=0;i<stringArray.length;i++){

        string=removeFromString(stringArray[i],string);

    }
    return string;
}
它循环遍历数组中的单词并逐个删除它们。

另一种方法是使用:

函数removeFromStringwords,str{ 返回words.reduceresult,word=>result.replaceword,str } const str=删除一个、两个,而不是三个和四个 const result=removeFromString[one,two,and four],str console.logresult您可以尝试以下方法:

function removeFromString(arr, str){
    arr.forEach(w => str = str.replace(w, ''));
    return str;
}
试试这个

函数replaceStrmyString,列表 { $.eachlist,functioni,item{ myString=myString.replace'Hello',item; }; } /*现在像这样使用这个功能*/ replaceStryourstring,arrayOfWords;
或replaceStryourString,{word1,word2};我只建议清理字符串以避免生成无效的regexp,并使其能够搜索特殊字符,如.,*,等等。。。更多信息:嗨,莫,请在你的答案中添加一个描述,说明这是如何解决问题的。