首页信息安全如果字符串中包含单词,请删除它们

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

admin 12-23 12:12 327次浏览

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

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

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

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)

这返回 My Awesome T-Something Else



1> Nina Scholz..:

您正在替换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)
如果字符串中包含单词请删除它们
使用Gulp进行多个SCSS编译 基于QT如何实现文件上传和下载功能
相关内容