【发布时间】:2019-12-24 18:08:54
【问题描述】:
我无法突出显示以space 开头并以某个字符开头的word。
这些字符在下面列出:
var list = ['Alex','&','2009','>','ph']; // 动态出现
问题:突出显示整个word,如果它以space 开头并以find search key 开头。在完全匹配的情况下突出显示它们。
测试用例:
1. with `ph` `Philip's` should highlight. not `.Philip's`
2. with `>` `>20` should highlight.
以下是我尝试过的:
var list = ['Alex','&','2009','>','ph']; // 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 in 2009 BC & 2010 BC. Alexander is > 20090 people. .>20 and >20.34&&() and 30> >`
var pattern = new RegExp(`(?<=(^|\\W))((\s\w*)${list.join('|')})(?=(\\W|$))`, 'ig')
var textDescription = textDescription.replace(pattern, '<highlight>$2</highlight>')
$('#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>
【问题讨论】:
-
您会反对使用数组和字符串匹配而不是冗长的 RegEx 的解决方案吗?
-
您是要匹配还是突出显示?正则表达式不是这项工作的工具。见How to highlight text using javascript
标签: javascript jquery regex