如果字符串中包含单词,请删除它们

K20*_*0GH 1 javascript

我有一个字符串,以及数组中的单词列表。

我想做的是说“如果此数组中的任何单词在字符串中,请将其删除”,然后“从字符串中删除双倍空格”

我快到了,但是由于某种原因,它没有注意破折号

const name = "My Awesome T-Shirt Something Else"    ;
    const words = [
          'V-Neck ',
          'Long Sleeve ',
          'T-Shirt ',
          'Pullover Hoodie ',
          'Raglan Baseball Tee ',
          'Tee ',
          'Zip Hoodie ',
          'Tank Top ',
          'Premium ',
          'Sweatshirt ',
          'PopSockets Grip and Stand for Phones and Tablets ',
          'Shirt '
        ];
        
    let newName = name;
    
         
    words.forEach(w => {
       if(name.includes(w)) newName = name.replace(w, '');
    });
    
    newName = newName.replace(/ +(?= )/g,'');
    
    console.log(newName)
Run Code Online (Sandbox Code Playgroud)

这返回 My Awesome T-Something Else

Nin*_*olz 5

您正在替换name而不是newName

const name = "My Awesome T-Shirt Something Else"    ;
const words = [
      'V-Neck ',
      'Long Sleeve ',
      'T-Shirt ',
      'Pullover Hoodie ',
      'Raglan Baseball Tee ',
      'Tee ',
      'Zip Hoodie ',
      'Tank Top ',
      'Premium ',
      'Sweatshirt ',
      'PopSockets Grip and Stand for Phones and Tablets ',
      'Shirt '
    ];

let newName = name;


words.forEach(w => {
   while (newName.includes(w)) newName = newName.replace(w, ''); // take a while for more than one occurences
   //     ^^^^^^^                        ^^^^^^^
});

newName = newName.replace(/ +(?= )/g,'');

console.log(newName)
Run Code Online (Sandbox Code Playgroud)

  • 同样适用于“ if”条件。如果您要处理`newName`,那么检查`name`是不好的样式。 (2认同)