【发布时间】:2019-12-23 17:44:52
【问题描述】:
假设我有这样的字符串列表['Alexander','&','2009','>']。
当它们出现在特定文本中时,我想在该列表中的每个关键字周围放置<highlight> 标签。
我试图解决这个问题,但我想避免使用for 循环,因为它似乎会导致像<highlight>Alexander<highlight>Alexander</highlight></highlight> 这样的嵌套,我想避免这种情况。
这是我尝试过的:
var list = ['Alexander','&','2009','>']; // comes dynamically
var textDescription = `Alexander the Great (Ancient Greek: Ἀλέξανδρος ὁ Μέγας, romanized: Aléxandros ho Mégas), was a king (basileus) of the ancient Greek kingdom of Macedon[a] and a member of the Argead dynasty. He was born in Pella in 356 BC and succeeded his father Philip II to the throne at the age of 20. He spent most of his ruling years on an unprecedented military campaign through Asia and northeast Africa, and by the age of thirty, he had created one of the largest empires of the ancient world, stretching from Greece to northwestern India.[1][2] He was undefeated in battle and is widely considered one of history's most successful military commanders.[3]
During his youth, Alexander was tutored by Aristotle until age 16. After Philip's assassination in 336 BC, he succeeded his father to the throne and inherited a strong kingdom `;
for(var i = 0; i < list.length; i++){
var searchText = list[i];
var pattern = new RegExp(`\\b${searchText}(?!([\w\s\.]*<\/highlight>))`,'ig');
var res = textDescription.replace(pattern,function(x){
return '<highlight>'+x+'</highlight>';
});
textDescription = res;
}
$('#highlight').html(textDescription);
highlight{
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="highlight"></div>
【问题讨论】:
标签: javascript jquery regex