如何在Javascript中从字符串中删除数组值

hxzsmxv2  于 2023-01-11  发布在  Java
关注(0)|答案(2)|浏览(139)

简单明了,如何从字符串中删除数组值,示例:

var String = "Hi my name is ftk: [2] what is yours? [ And how are 2 5 you? [1] Are you ok?"
var array = [ "[1]", "[2]" ]

---OUTPUT---

"Hi my name is ftk: what is yours? [ and how are 2 5 you? Are you ok?"

基本上我只想删除一个特定的数组,并且只有当它是完全相同的单词时,如果它有意义的话.
我试过.replace with global,但我不能在那里使用数组,我只能输入一个特定的字符串,如:

var string2 = string.replace(/\[1|\]/g, '');

看上面,我不能同时删除2个单词,而且每次我添加一个特定的单词要删除时,手动创建一个新的变量会很糟糕,所以数组是最好的。
先谢了。

c0vxltue

c0vxltue1#

你可以在数组中循环,并在循环过程中替换每个数组项:

let string = "Hi my name is ftk: [2] what is yours? [ And how are 2 5 you? [1] Are you ok?"
let array = [ "[1]", "[2]" ]

for (let i = 0; i < array.length; i++) {
    string = string.replace(array[i], '');
}

console.log(string);
p4tfgftt

p4tfgftt2#

你可以使用一个字符类来定义多个要移除的匹配项,然后在replace的回调函数中,检查匹配项是否出现在array中。

\[[12]]

示例

var string2 = string.replace(/\[[12]]/g, '');
var string = "[3] Hi my name is ftk: [2][2] what is yours? [ And how are 2 5 you? [1] Are you ok?"
var array = ["[1]", "[2]"];
var string2 = string.replace(
  /\[[12]]/g,
  m => array.includes(m) ? '' : m
);
console.log(string2);

相关问题