代码之家  ›  专栏  ›  技术社区  ›  seriously

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

  •  0
  • seriously  · 技术社区  · 1 年前

    我有一个字符串数组和一个动态生成的变量 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)
    1 回复  |  直到 1 年前
        1
  •  3
  •   noah1400    1 年前

    您可以使用正则表达式:

    // 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 函数用于转义单词中的任何特殊regex字符。
    • \\b 在regex中,确保只有完整的单词匹配(避免部分匹配)。
    • 这个 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(' ');
    

    这也更容易阅读和理解。

        2
  •  0
  •   Ali Mustafa    1 年前

    这是一种方法。我不知道高效在上下文中意味着什么。我正在使用 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.replace(y+' ', '');
    })
    console.log(x)