我有一个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>
答案 0 :(得分: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);
答案 1 :(得分: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);
答案 2 :(得分: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(' '));
答案 3 :(得分: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标记。