http://jsfiddle.net/nHGU6/
測試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:
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 });
});
查看來自casablanca的答案:http://stackoverflow.com/questions/4261740/accent-insensitive-regex。基本上,圍繞jquery.highlight.js的第91行進行修改,以便正則表達式現在包含字符類。可能會在第83行附近添加「accentInsensitive」選項。 – anon 2011-05-20 04:16:35
謝謝,但是我對如何在代碼中實現該代碼感到有點遺憾... – Santiago 2011-05-20 21:28:39
好的。我在下面添加了一個實現。 – anon 2011-05-21 01:23:04