I have a sentence, and I want to remove some words from it.
So if I have:
"jQuery is a Unique language"
and an array that is named garbageStrings:
var garbageStrings = ['of', 'the', "in", "on", "at", "to", "a", "is"];
I want to remove the "is" and "a" in the sentence.
But if I use this: /This statement is inside a for loop. I'm looping the whole sentence and finding a match in the garbageStrings/
var regexp = new RegExp(garbageStrings[i]);
the string will become "jQuery Unique lnguge"
Notice that the "a" in language is removed from the sentence.
I didn't intend that to happen.
Something like this:
function keyword(s) {
var words = ['of', 'the', 'in', 'on', 'at', 'to', 'a', 'is'];
var re = new RegExp('\\b(' + words.join('|') + ')\\b', 'g');
return (s || '').replace(re, '').replace(/[ ]{2,}/, ' ');
}
I could have sworn JavaScript had \b
(word boundary), but it looks like it doesn't, try this instead:
var regex = new RegExp("( |^)" + "a" + "( |$)", "g");
var string = "I saw a big cat, it had a tail.";
string = string.replace(regex, "$1$2");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With