如何在Javascript中从字符串中删除一个单词数组?

3

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

  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 str = "Remove one, two, not three and four"; 

在这里,我们需要移除 "one"、"two" 和 "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

在上面的例子中,我不得不两次使用该函数。我希望它像这样:
 var c = removeFromString(["one, two," , "and four"], str); // Remove not three
 console.log(c); // Remove not three

是的,我确实想升级removeFromString函数!我该怎么做?

6个回答

5

您可以使用join从数组动态构建正则表达式,并替换匹配的值。

function removeFromString(arr,str){
  let regex = new RegExp("\\b"+arr.join('|')+"\\b","gi")
  return str.replace(regex, '')
}

console.log(removeFromString(["one, two," , "and four"],"Remove one, two, not three and four" ));
console.log(removeFromString(["one" , "and four"],"Remove one, two, not three and four" ));
console.log(removeFromString(["Hello"], "Hello World") )

为了涵盖您所匹配的单词可能具有元字符的情况,您可以按照以下方式扩展上面的示例。

function escape(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};

function removeFromString(arr, str) {
  let escapedArr = arr.map(v=> escape(v))
  let regex = new RegExp("(?:^|\\s)"+escapedArr.join('|') + "(?!\\S)", "gi")
  return str.replace(regex, '')
}

console.log(removeFromString(["one, two,", "and four"], "Remove one, two, not three and four"));
console.log(removeFromString(["one", "and four"], "Remove one, two, not three and four"));
console.log(removeFromString(["Hello"], "Hello World"))
console.log(removeFromString(["He*llo"], "He*llo World"))
console.log(removeFromString(["Hello*"], "Hello* World"))


我建议对字符串进行清理以避免构建无效的正则表达式,并使其能够搜索特殊字符,例如“.”,“*”等。更多信息请参见:这里 - Christian C. Salvadó

4

使用reduce方法的另一种方法:

function removeFromString(words, str) {
  return words.reduce((result, word) => result.replace(word, ''), str)
}

const str = "Remove one, two, not three and four"
const result  = removeFromString(["one, two, " , "and four"], str)

console.log(result)


很好地使用了 Array.prototype.reduce。只有一个备注:如果你想替换所有出现的 单词,最好使用 replaceAll 而不是 replace - cezar

2
你可以尝试这个:
function removeFromString(arr, str){
    arr.forEach(w => str = str.replace(w, ''));
    return str;
}

嗨Mo,请在你的答案中添加一个描述,说明这如何解决问题。 - Murray Foxcroft

0

试试这个

function replaceStr(myString,list)
  {
    $.each(list,function(i,item){
    myString=myString.replace('Hello', item);
    });   
  }
  
  /*Now use this fucntion like this */
replaceStr(yourstring,arrayOfWords);
or replaceStr(yourString,{"word1","word2"});


0
wordArray.forEach(word => {
    sentence = sentence.replace(word, '');
})

0
你需要像这样的东西:
function newRemoveFromString(stringArray,string){

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

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

    }
    return string;
}

它会循环遍历数组中的单词,并逐一将其移除。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接