1

我有一个js字符串...

var string = "Hi how are you <b>today</b>";

我现在有一个新的 js 字符串...

var newstring = "are today";

我想删除所有var string不匹配的单词var newstring。如果有的话,我还想保留与这些词相关联的标签。

Example Result:
are <b>today</b> 
4

4 回答 4

3

有一些简单的方法可以做这样的事情,如果它们对你有用,取决于你打算用它做什么,但可能是这样的:

var string = "Hi how are you <b>today</b>",
    newstring = "are today",
    words = newstring.split(' ');

for (var i=0; i<words.length; i++) {
    var reg = new RegExp(words[i], 'gi');
    string = string.replace(reg, '');
}

console.log(string);​

小提琴

于 2012-04-16T17:16:40.120 回答
0
var string = "Hi how are you <b>today</b>",
    newstring = "are today",
    words= newstring.split(' ');
$.each(words, function(i, v) {
    if(new RegExp(v, 'ig').test(string) && !new RegExp('<b>'+v+'</b>', 'ig').test(string)) {
        string = string.replace(v,'');
    }
});
console.log(string);
于 2012-04-16T17:21:56.250 回答
0
var source = "Hi how are you <b>today</b>",
    pattern = "are today",
    res = [];

pattern.split(/\s+/).forEach(function( word ) {
    source.split(/\s+/).forEach(function( sWord ) {
        if( ~sWord.indexOf(word) ) res.push( sWord );
    });
});

console.log(res.join(' '));
于 2012-04-16T17:22:43.117 回答
0
var str = 'Hi how are you <b>today</b>',
    words = ['are', 'today']; //or 'are today'.split(' '),
    regex = new RegExp('(<[a-zA-Z]*>)?(' + words.join('|') + ')(</[a-zA-Z]*>)?', 'g');

console.log(regex, str.match(regex), str.match(regex).join(' '));

不过,您将需要一个更复杂的正则表达式来捕获所有 HTML 标记。

http://jsfiddle.net/g7xQx/

于 2012-04-16T17:25:23.000 回答