如何从 JavaScript 中的字符串中删除单词数组?

Arc*_*Arc 3 javascript arrays

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

  var removeFromString = function(oldStr, fullStr) { 
    return fullStr.split(oldStr).join(''); 
  };
Run Code Online (Sandbox Code Playgroud)

我这样使用它:

 console.log( removeFromString("Hello", "Hello World") ); // World
 console.log( removeFromString("Hello", "Hello-World") ); // -World
Run Code Online (Sandbox Code Playgroud)

但主要问题是:

 var str = "Remove one, two, not three and four"; 
Run Code Online (Sandbox Code Playgroud)

这里我们必须删除“一”、“二”和“四”。这可以通过以下方式完成:

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
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我不得不使用该函数两次。我希望它是这样的:

 var c = removeFromString(["one, two," , "and four"], str); // Remove not three
 console.log(c); // Remove not three
Run Code Online (Sandbox Code Playgroud)

是的,我实际上想升级removeFromString函数!我怎样才能做到这一点 ?

Cod*_*iac 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") )
Run Code Online (Sandbox Code Playgroud)


为了涵盖要匹配的单词可以包含元字符的情况,您可以通过这种方式扩展上面的示例

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"))
Run Code Online (Sandbox Code Playgroud)