javascript 如果在数组中找到字符串中出现的单词,则删除所有单词

egdjgwm8  于 12个月前  发布在  Java
关注(0)|答案(2)|浏览(114)

我有一个字符串数组和一个动态生成的变量x。我想做的是删除变量x中的所有出现,如果它们在数组中找到。检查下面以更好地理解我的问题。

**注意:**数组应该包含很多元素,所以代码效率越高越好。此外,可能会有多个单词出现,如果在myArr中找到,必须将它们全部删除

//expected to contain a lot of elements
myArr = ["test", "green", "blah", "foo", "bar"]

//dynamic variable
x = "this is my test string with color green"

//dumb approch 
x = x.replaceAll("test", "").replaceAll("green", "").replaceAll("blah", "").replaceAll("foo", "").replaceAll("bar", "")

//expected result is the x string with the words inside myArr removed
console.log(x)

字符串

ldioqlga

ldioqlga1#

你可以使用正则表达式:

// Array containing the words to remove
const myArr = ["test", "green", "blah", "foo", "bar"];

// Dynamic variable
let x = "this is my test string with color green";

// Create a regular expression that matches any word in myArr, including optional spaces around the word
const regexPattern = myArr.map(word => `\\s*${word.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')}\\s*`).join('|');
const regex = new RegExp(`(${regexPattern})`, 'gi');

// Replace all occurrences of the words in x, including surrounding spaces
x = x.replace(regex, ' ').trim();

// Replace multiple spaces with a single space
x = x.replace(/\s+/g, ' ');

// Log the result
console.log(x);

字符串
代码说明:

  • map函数用于转义单词中的任何特殊正则字符。
  • 正则表达式中的\\b确保只匹配整个单词(避免部分匹配)。
  • gi标志使regex全局(影响所有出现的情况)且不区分大小写。
  • 然后,replace方法将所有匹配的单词替换为空字符串。

编辑

如果数组元素包含括号和括号,则需要在转义逻辑中包含括号和括号。此外,'\\b'单词边界可能无法按预期工作,因此您可能需要使用不同的方法来防止部分匹配。

// Array containing the words to remove
const myArr = ["(test)", "green", "blah", "foo", "bar"];

// Dynamic variable
let x = "this is my (test) string with color green";

// Function to escape special characters
const escapeRegExp = (word) => word.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

// Create a regular expression that matches any word in myArr
const regexPattern = myArr.map(escapeRegExp).join('|');
const regex = new RegExp(`(?:^|\\s)(${regexPattern})(?:$|\\s)`, 'gi');

// Replace all occurrences of the words in x
x = x.replace(regex, ' ').trim();

// Log the result
console.log(x);

编辑2

解决这个问题的另一种方法是将字符串拆分为单词,并过滤掉数组中的单词。

// Split the string into words
let words = x.split(/\s+/);

// Filter out words that are in myArr
words = words.filter(word => !myArr.includes(word));

// Join the words back into a string
x = words.join(' ');


这也更容易阅读和理解。

sqyvllje

sqyvllje2#

这是一种方法。我不知道高效在上下文中是什么意思。我使用every来遍历字符串并逐个删除每个元素。

//expected to contain a lot of elements
myArr = ["test", "green", "blah", "foo", "bar"]

//dynamic variable
x = "this is my test string with color green"

//dumb approch 
myArr.every((y)=>{
  x = x.replaceAll(y+' ', '');
})
console.log(x)

字符串

相关问题