Remove Stop Words in JavaScript

Sometimes it may be useful to remove stop words from strings, when parsing data in JavaScript. I found myself in that situation with a recent project. I looked around for a String method to do this, but didn’t have much luck, so I wrote my own.

Stop words are typically things like conjunctions, prepositions, etc. Typically, a developer would want to remove stop words from a string, in order to extract keywords from it. I found a stop word list after a quick search, and used it in my method. The method I wrote actually extends the JavaScript String data type, so it can be applied to any string. You just have to be sure to define the prototype method before calling it.

Once you’ve defined it, you just call the method like this:

foo = "here is a string that has some stop words in it";
bar = foo.removeStopWords();
// The value of bar will be "string stop words"

The method works by first defining a very large array with stop words in it. The string itself is split by whitespaces within the string, creating an array of contiguous non-whitespace characters. There are then two loops for processing the words.

The outer loop cycles through all of the words in the string, and the inner loop cycles through all of the stop words. The inner loop performs a comparison between the current word and current stopword. If the word matches the stop word, all instances of it are removed from the main string.

Here’s the code:

 * String method to remove stop words
 * Written by GeekLad
 * Stop words obtained from
 *   Usage: string_variable.removeStopWords();
 *   Output: The original String with stop words removed
String.prototype.removeStopWords = function() {
	var x;
	var y;
	var word;
	var stop_word;
	var regex_str;
	var regex;
	var cleansed_string = this.valueOf();
	var stop_words = new Array(
	// Split out all the individual words in the phrase
	words = cleansed_string.match(/[^\s]+|\s+[^\s+]$/g)

	// Review all the words
	for(x=0; x < words.length; x++) {
		// For each word, check all the stop words
		for(y=0; y < stop_words.length; y++) {
			// Get the current word
			word = words[x].replace(/\s+|[^a-z]+/ig, "");	// Trim the word and remove non-alpha
			// Get the stop word
			stop_word = stop_words[y];
			// If the word matches the stop word, remove it from the keywords
			if(word.toLowerCase() == stop_word) {
				// Build the regex
				regex_str = "^\\s*"+stop_word+"\\s*$";		// Only word
				regex_str += "|^\\s*"+stop_word+"\\s+";		// First word
				regex_str += "|\\s+"+stop_word+"\\s*$";		// Last word
				regex_str += "|\\s+"+stop_word+"\\s+";		// Word somewhere in the middle
				regex = new RegExp(regex_str, "ig");
				// Remove the word from the keywords
				cleansed_string = cleansed_string.replace(regex, " ");
	return cleansed_string.replace(/^\s+|\s+$/g, "");

About GeekLad

Geeklad is a technology enthusiast and programming hobbyist. Occasionally he will put together useful little bits of code (be it JavaScript or PHP) and share them with the world. He also enjoys creating and sharing howtos, describing how to do the things people want to do with their computers.
Tagged . Bookmark the permalink.
  • ankitech

    © ® 2013 by kumar and john

    //testbox and search buttons used by us to test

    //script to be added


    * This is the function that actually highlights a text string by

    * adding HTML tags before and after all occurrences of the search

    * term. You can pass your own tags if you’d like, or if the

    * highlightStartTag or highlightEndTag parameters are omitted or

    * are empty strings then the default tags will be used.


    function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag)


    // the highlightStartTag and highlightEndTag parameters are optional

    if ((!highlightStartTag) || (!highlightEndTag)) {

    highlightStartTag = “”;

    highlightEndTag = “”;


    // find all occurences of the search term in the given text,

    // and add some “highlight” tags to them (we’re not using a

    // regular expression search, because we want to filter out

    // matches that occur within HTML tags and script blocks, so

    // we have to do a little extra validation)

    var newText = “”;

    var i = -1;

    var lcSearchTerm = searchTerm.toLowerCase();

    var lcBodyText = bodyText.toLowerCase();

    while (bodyText.length > 0) {

    i = lcBodyText.indexOf(lcSearchTerm, i+1);

    if (i “, i) >= bodyText.lastIndexOf(“<", i)) {

    // skip anything inside a block

    if (lcBodyText.lastIndexOf(“/script>”, i) >= lcBodyText.lastIndexOf(“<script", i)) {

    newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;

    bodyText = bodyText.substr(i + searchTerm.length);

    lcBodyText = bodyText.toLowerCase();

    i = -1;





    return newText;



    * This is sort of a wrapper function to the doHighlight function.

    * It takes the searchText that you pass, optionally splits it into

    * separate words, and transforms the text on the current web page.

    * Only the "searchText" parameter is required; all other parameters

    * are optional and can be omitted.


    function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag)


    // if the treatAsPhrase parameter is true, then we should search for

    // the entire phrase that was entered; otherwise, we will split the

    // search string so that each word is searched for and highlighted

    // individually

    if (treatAsPhrase) {

    searchArray = [searchText];

    } else {

    searchArray = searchText.split(" ");


    if (!document.body || typeof(document.body.innerHTML) == "undefined") {

    if (warnOnFailure) {

    alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");


    return false;


    var bodyText = document.body.innerHTML;

    for (var i = 0; i < searchArray.length; i++) {

    bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);


    document.body.innerHTML = bodyText;

    return true;



    * This displays a dialog box that allows a user to enter their own

    * search terms to highlight on the page, and then passes the search

    * text or phrase to the highlightSearchTerms function. All parameters

    * are optional.


    function stopwordSearch(defaultText)


    //alert("stop promp");

    var my_stop_words = new Array("a","able","about","above","according","accordingly","across","actually","after","afterwards","again","against","all",





































    var text = defaultText.toLowerCase();

    var res=(my_stop_words.indexOf(text) <= 0) ? true : false;

    return res;


    function searchPrompt(defaultText, treatAsPhrase, textColor, bgColor)


    //alert("searched promp");

    //search for keyword is a stop word or not

    var result= stopwordSearch(defaultText);

    if(result == true)


    // This function prompts the user for any words that should

    // be highlighted on this web page

    if (!defaultText) {

    defaultText = "";


    // we can optionally use our own highlight tag values

    if ((!textColor) || (!bgColor)) {

    highlightStartTag = "";

    highlightEndTag = "";

    } else {

    highlightStartTag = "”;

    highlightEndTag = “”;


    if (treatAsPhrase) {

    promptText = “Please enter the phrase you’d like to search for:”;

    } else {

    promptText = “Please enter the words you’d like to search for, separated by spaces:”;


    //searchText = prompt(promptText, defaultText);

    searchText = defaultText;

    if (!searchText) {

    alert(“No search terms were entered. Exiting function.”);

    return false;






    return highlightSearchTerms(searchText, treatAsPhrase, true, highlightStartTag, highlightEndTag);




    alert(“keyword not valid try again”);