javascript正则表达式-替换字符串停止字
我试图编写一个函数,从字符串中删除特定的单词 下面的代码在句子的最后一个单词之前都可以正常工作,因为它后面没有我的正则表达式要查找的空格 如何捕获后面没有空格的最后一个单词 您可以使用: 您可以使用:javascript正则表达式-替换字符串停止字,javascript,regex,string,Javascript,Regex,String,我试图编写一个函数,从字符串中删除特定的单词 下面的代码在句子的最后一个单词之前都可以正常工作,因为它后面没有我的正则表达式要查找的空格 如何捕获后面没有空格的最后一个单词 您可以使用: 您可以使用: 假设我在word上经过sea stopwords( "this is a test string sea mentioning the word across and a about"); 这将减少sea到se function stopwords(input) { var stop_w
假设我在word上经过
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
假设我在word上经过
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