0

文字列から特定の単語を削除する関数を作成しようとしています。

以下のコードは、私の正規表現が検索するスペースが後に続かないため、文の最後の単語まで問題なく機能します。

スペースが続かない最後の単語をキャプチャするにはどうすればよいですか?

JSフィドル

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");
4

2 に答える 2

2

境界マーカーという単語を使用できます。

var reg = new RegExp(item +'\\b','gi')
于 2013-03-16T17:28:17.887 に答える
1

私がsea言葉を伝えているとしましょう

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

に削減さseaれます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");

出力があります

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  
于 2013-03-16T17:57:12.890 に答える