1

I have a string, and a list of words in an array.

What I want to do is say "If any words in this array are in the string, remove them" and then "remove an double spaces from the string"

I'm almost there, but for some reason it's not paying attention to the dash

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)

This returns My Awesome T-Something Else

0

1 Answer 1

5

You are replacing name and not 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)

Sign up to request clarification or add additional context in comments.

1 Comment

Same applies to the if condition. It is bad style to check name, if you deal with newName.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.