有趣的问题——这是我可能会如何做的一个想法:http://jsfiddle.net/SaQAs/1/——无论如何都没有优化!
var text = $('p').text(),
words = text.split(' '),
sortedWords = words.slice(0).sort(),
duplicateWords = [],
sentences = text.split('.'),
sortedSentences = sentences.slice(0).sort(),
duplicateSentences = [];
for (var i=0; i<sortedWords.length-1; i++) {
if (sortedWords[i+1] == sortedWords[i]) {
duplicateWords.push(sortedWords[i]);
}
}
duplicateWords = $.unique(duplicateWords);
for (var i=0; i<sortedSentences.length-1; i++) {
if (sortedSentences[i+1] == sortedSentences[i]) {
duplicateSentences.push(sortedSentences[i]);
}
}
duplicateSentences = $.unique(duplicateSentences);
$('a.words').click(function(){
var highlighted = $.map(words, function(word){
if ($.inArray(word, duplicateWords) > -1)
return '<span class="duplicate">' + word + '</span>';
else return word;
});
$('p').html(highlighted.join(' '));
return false;
});
$('a.sentences').click(function(){
var highlighted = $.map(sentences, function(sentence){
if ($.inArray(sentence, duplicateSentences) > -1)
return '<span class="duplicate">' + sentence + '</span>';
else return sentence;
});
$('p').html(highlighted.join('.'));
return false;
});
更新 1
这个找到相同单词的序列:http://jsfiddle.net/YQdk5/1/ 从这里它应该不难,例如比较时忽略片段末尾的任何标点符号——您只需要编写自己的 inArray 方法版本。
var text = $('p').text(),
words = text.split(' '),
sortedWords = words.slice(0).sort(),
duplicateWords = []
highlighted = [];
for (var i=0; i<sortedWords.length-1; i++) {
if (sortedWords[i+1] == sortedWords[i]) {
duplicateWords.push(sortedWords[i]);
}
}
duplicateWords = $.unique(duplicateWords);
for (var j=0, m=[]; j<words.length; j++) {
m.push($.inArray(words[j], duplicateWords) > -1);
if (!m[j] && m[j-1])
highlighted.push('</span>');
else if (m[j] && !m[j-1])
highlighted.push('<span class="duplicate">');
highlighted.push(words[j]);
}
$('p').html(highlighted.join(' '));
更新 2
我的 regex-fu 很弱,但是这个(相当混乱!)版本似乎可以正常工作:http://jsfiddle.net/YQdk5/2/ - 我很确定可能有更好的方法来做到这一点,但现在我有别管它! :D — 祝你好运!
更新 3
想一想,我不认为上次更新的代码有什么好处。这就是我删除它的原因。你仍然可以在这里找到它:http://jsfiddle.net/YQdk5/2/
要点是使用正则表达式来匹配单词,类似于:
/^word(\.?)$/