2013-03-16 48 views
0

我想寫一個函數,從字符串中刪除特定的單詞。JavaScript的正則表達式 - 替換字符串停用詞

下面的代碼工作正常,直到句子的最後一個單詞,因爲它沒有跟着我的正則表達式尋找的空間。

我怎樣才能捕捉到最後一個沒有空格的單詞?

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

回答

1

想我傳遞sea上字

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

這將減少sease

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 
2

您可以使用word boundary marker

var reg = new RegExp(item +'\\b','gi') 
+0

當然!謝謝! – Ben 2013-03-16 17:33:52