Remove stopwords with javascript and regex

javascript, regex, stop-words, variables

Solution

Something like this maybe

str = str.replace(new RegExp('\\b('+stopwords.join('|')+')\\b', 'g'), '');

FIDDLE

You have to double escape in RegExp, and you could just join everything creating

/\b(as|at|he|the|was)\b/g

Problem

I want to remove stopwords from text but fail to use regex and variables properly. For example I remove the stopword "he" but this also affects the word "when". I tried to use word boundaries like this: `new RegExp('\b'+stopwords[i]+'\b' , 'g')` but doesn't work... See a small example here: jsFiddle ``` var stopwords = ['as', 'at', 'he', 'the', 'was']; for (i = 0; i < stopwords.length; i++) { str = str.replace(new RegExp(stopwords[i], 'g'), ''); } ```

Original source