Допустим, у меня есть список таких строк ['Alexander','{amp}amp;','2009','{amp}gt;'] .

Я хочу разместить теги {amp}lt;highlight{amp}gt; вокруг каждого ключевого слова в этом списке, когда они появляются в определенном тексте.

Я пытался решить эту проблему, но я хочу избежать использования цикла for потому что он, кажется, вызывает вложение, как этот {amp}lt;highlight{amp}gt;Alexander{amp}lt;highlight{amp}gt;Alexander{amp}lt;/highlight{amp}gt;{amp}lt;/highlight{amp}gt; и я хочу избежать этого.

Вот что я попробовал:

 var list = ['Alexander','{amp}amp;','2009','{amp}gt;']; // 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 {amp}lt; list.length; i  ){ var searchText = list[i]; var pattern = new RegExp(`\b${searchText}(?!([ws.]*{amp}lt;/highlight{amp}gt;))`,'ig'); var res = textDescription.replace(pattern,function(x){ return '{amp}lt;highlight{amp}gt;' x '{amp}lt;/highlight{amp}gt;'; }); textDescription = res; } $('#highlight').html(textDescription); 
 highlight{ color: red; } 
 {amp}lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"{amp}gt;{amp}lt;/script{amp}gt; {amp}lt;div id="highlight"{amp}gt;{amp}lt;/div{amp}gt; 

Я разработал решение для вас.

Я упростил твой код. Вам не нужно иметь петлю. Вы можете просто объединить массив вместе с разделителем | , служа оператором OR чтобы любая найденная строка была окружена тегами.

Вы увидите, что я добавил некоторый текст в конец того, что вы положили, чтобы можно было проверить все строки, а также когда они будут найдены в середине другой строки, например, 2009 в 2009 году.

РЕДАКТИРОВАТЬ: я обновил этот ответ и удалил литералы шаблона и обходные пути, чтобы иметь лучшую совместимость со старыми браузерами и IE и т. Д.

 var list = ['Alexander','{amp}amp;','2009','{amp}gt;'] 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] nDuring 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 in 2009 BC {amp}amp; 2010 BC. Alexander is {amp}gt; 20090 people." var pattern = new RegExp("(^|\W)(" list.join('|') ")(\W|$)", 'ig') var textDescription = textDescription.replace(pattern, '$1{amp}lt;highlight{amp}gt;$2{amp}lt;/highlight{amp}gt;$3') $('#highlight').html(textDescription) 
 highlight { color: red; } 
 {amp}lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"{amp}gt;{amp}lt;/script{amp}gt; {amp}lt;div id="highlight"{amp}gt;{amp}lt;/div{amp}gt;