在jQuery中突出显示带有(或不带有)带重音符号/变音符号的单词 [英] Highlight words with (and without) accented characters / diacritics in jQuery
问题描述
我正在使用jquery.highlight插件: http://code.google.com/p/gce-empire/source/browse/trunk/jquery.highlight.js?r=2
I'm using the jquery.highlight plugin: http://code.google.com/p/gce-empire/source/browse/trunk/jquery.highlight.js?r=2
我用它来突出显示搜索结果.
I'm using it to highlight search results.
问题是,如果我搜索类似café" 之类的内容,则不会突出显示任何单词.
The problem is that if I search something like "café" it won't highlight any words.
如果我搜索"cafe" ,即使我的搜索结果同时包含"cafe" 和& 咖啡馆" ,它将仅突出显示咖啡馆" .
And if I search "cafe", even though my results contains both "cafe" & "café", it will only highlight "cafe".
因此,无论是否带有变音符号,我都需要突出显示单词的所有版本".
So, I would need to highlight all "versions" of the words, with or without diacritics.
有可能吗?
推荐答案
测试HTML:
<div id="wrapper-accent-sensitive">
<p>cafe</p>
<p>asdf</p>
<p>café</p>
</div>
<hr />
<div id="wrapper-not-accent-sensitive">>
<p>cafe</p>
<p>asdf</p>
<p>café</p>
</div>
测试CSS:
.yellow {
background-color: #ffff00;
}
替换Javascript:
Replacement Javascript:
jQuery.fn.highlight = function (words, options) {
var accentedForms = {
'c': 'ç',
'e': 'é'
};
var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false, accentInsensitive: false };
jQuery.extend(settings, options);
if (settings.accentInsensitive) {
for (var s in accentedForms) {
words = words.replace(s, '[' + s + accentedForms[s] + ']');
}
}
if (words.constructor === String) {
words = [words];
}
var flag = settings.caseSensitive ? "" : "i";
var pattern = "(" + words.join("|") + ")";
if (settings.wordsOnly) {
pattern = "\\b" + pattern + "\\b";
}
var re = new RegExp(pattern, flag);
return this.each(function () {
jQuery.highlight(this, re, settings.element, settings.className);
});
};
测试代码:
$(document).ready(function() {
$("#wrapper-accent-sensitive").highlight("cafe", { className: 'yellow' });
$("#wrapper-not-accent-sensitive").highlight("cafe", { className: 'yellow', accentInsensitive: true });
});
这篇关于在jQuery中突出显示带有(或不带有)带重音符号/变音符号的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!