0

I am trying to write a function that removes specific words from a string.

The below code works ok until the last word of the sentence, as it is not followed by a space that my regex looks for.

How can I capture the last word that is not followed by a space?

JS Fiddle

function stopwords(input) {

var stop_words = new Array('a', 'about', 'above', 'across');

console.log('IN: ' + input);

stop_words.forEach(function(item) {
    var reg = new RegExp(item +'\\s','gi')

    input = input.replace(reg, "");
});

console.log('OUT: ' + input);
}

stopwords( "this is a test string mentioning the word across and a about");

2 Answers 2

2

You may use the word boundary marker :

var reg = new RegExp(item +'\\b','gi')
Sign up to request clarification or add additional context in comments.

Comments

1

suppose I am passing sea on word

stopwords( "this is a test string sea mentioning the word across and a about");

which will cut down sea to se

function stopwords(input) {

  var stop_words = ['a', 'about', 'above', 'across'];

  console.log('IN: ' + input);

  // JavaScript 1.6 array filter
  var filtered  = input.split( /\b/ ).filter( function( v ){
        return stop_words.indexOf( v ) == -1;
  });

  console.log( 'OUT 1 : ' + filtered.join(''));

  stop_words.forEach(function(item) {
      // your old : var reg = new RegExp(item +'\\s','gi');
      var reg = new RegExp(item +'\\b','gi'); // dystroy comment

      input = input.replace(reg, "");
  });

  console.log('OUT 2 : ' + input);
}

stopwords( "this is a test string sea mentioning the word across and a about");

which has output

IN: this is a test string sea mentioning the word across and a about

OUT 1 : this is  test string sea mentioning the word  and  

OUT 2 : this is  test string se mentioning the word  and  

Comments

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.