Javascript - Regex rule, find XX but not in span tag
Text
message = 'Hello, my name ist Peter!';
My Tags
tags = {};
tags.tagsOne = {};
tags.tagsOne['t1'] = 'hello|is|there|g';
tags.tagsOne['t2'] = 'bub';
tags.tagsOne['t3'] = 'dog|house';
tags.tags开发者_高级运维Two = {};
tags.tagsTwo['t1'] = 'blub|man';
tags.tagsTwo['t2'] = 'word';
tags.tagsTwo['t3'] = 'sorry|high';
Regex
regexT1 = new RegExp('('+tags.tagsOne['t1']+'|'tags.tagsTwo['t1']+')','gi');
regexT2 = new RegExp('('+tags.tagsOne['t2']+'|'tags.tagsTwo['t2']+')','gi');
regexT3 = new RegExp('('+tags.tagsOne['t3']+'|'tags.tagsTwo['t3']+')','gi');
Replace
message = message.replace(regexT1,'<span class="highlightT1">$1</span>');
message = message.replace(regexT2,'<span class="highlightT2">$1</span>');
message = message.replace(regexT3,'<span class="highlightT3">$1</span>');
He finds and replaces the <span class="highlightT1">$1</span>
too.
<span class="highlightT1">$1</span>
Example
-> http://jsfiddle.net/tVmTe/3/UPDATE:
Working example -> http://jsfiddle.net/tVmTe/9/Split the message on space and consider each word individually.
var words = message.split(' '),
var i = 0;
for(i; i < words.length; ++i){
if(regexT1.test(words[i])){
words[i] = words[i].replace(regexT1,'<span class="highlightT1">$1</span>');
continue;
}
//...
}
message = words.join(' ');
精彩评论