我有一个字符串和一个数组中的单词列表。
我想做的是说“如果这个数组中的任何单词在字符串中,删除它们”然后“从字符串中删除双空格”
我快到了,但出于某种原因它没有注意破折号
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
最佳答案
您正在替换 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)
关于javascript - 如果字符串包含数组中的单词,则将其删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56790959/