2011-11-22 56 views
0

在下面的脚本,我想强调所有的单词在句子建议改善脚本

function SearchQueue(text) 
{ 
    if(text !== null) 
    { 
    text = text.replace(/“/g, "\""); 
    text = text.replace(/”/g, "\""); 
    text = text.replace(/’/g, "\'"); 
    text = text.replace(/‘/g, "\'"); 
    text = text.replace(/–/g, "\-"); 
    text = text.replace(/ +(?=)/g,''); 
    $.trim(text); 
    text = text.replace(/\d\.\s+|[a-z]\)\s+|•\s+|[A-Z]\.\s+|[IVX]+\.\s+/g, ""); 
    text = text.replace(/([0-9A-Z]+[.)]|•)\s+/gi, ""); 
    text = text.replace(/(\r\n|\n|\r)/gm," "); 
    } 
    var words = text.split(' '); 
    for(var i=0;i<words.length;i++) 
     $('*').highlight(''+words[i]+''); // Will highlight the script with background color 
} 

但是,这使我的页面“反应迟钝”。请建议我改进脚本...

+0

多少字呢?而且,空串不是必需的。 – Ryan

+0

计数会很高... – Exception

+2

'/ +(?=)/'的含义是什么?一个或多个空间后跟一个空格?你可以用'/ + /'来简化它,并用一个空格代替。 –

回答

2

您在每次迭代中选择整个dom树,这可能解释为无响应。 尝试以下操作:

var body = $('body'); // since thats where all the text should live 
for(var i=0;i<words.length;i++){ 
    body.highlight(''+words[i]+''); // Will highlight the script with background color 
} 
+0

我会试一试..这是一个非常好的主意。 – Exception

+0

工作得很好谢谢 – Exception

1

您可以结合几个使用匹配评价你取代了(不知道JavaScript调用他们什么)。

例如:http://jsfiddle.net/zyqVE/

function match_eval(m){ 
    switch (m){ 
     case "“":case "”": 
      return "\""; 
     case "‘":case "’": 
      return "'"; 
     // etc... 

    } 
    return m; 
} 


alert("this “i“ a test".replace(/[““’‘–]/g, match_eval)); 

上下文:

function match_eval(m){ 
    switch (m){ 
     case "“":case "”": 
      return "\""; 
     case "‘":case "’": 
      return "'"; 
     case "–" 
      return "-"; 

    } 
    return m; 
} 

function SearchQueue(text) 
{ 
    if(text !== null) 
    { 
    text = text.replace(/[“”’‘–]/g, match_eval); 
    text = text.replace(/ +(?=)/g,''); 
    $.trim(text); 
    text = text.replace(/\d\.\s+|[a-z]\)\s+|•\s+|[A-Z]\.\s+|[IVX]+\.\s+/g, ""); 
    text = text.replace(/([0-9A-Z]+[.)]|•)\s+/gi, ""); 
    text = text.replace(/(\r\n|\n|\r)/gm," "); 
    } 
    var words = text.split(' '); 
    for(var i=0;i<words.length;i++) 
     $('*').highlight(''+words[i]+''); // Will highlight the script with background color 
} 
+0

看起来非常有趣......你能否在当前的功能中实现它。 – Exception

+0

非常感谢:-) – Exception

1

这是我的第一套调整:

var $all = $('*'); 

function SearchQueue(text) { 
    if(text) { 
     text = text.replace(/[“”]/g, '"'); 
     text = text.replace(/[’‘]/g, "'"); 
     text = text.replace(/–/g, '-'); 
     text = text.replace(/\s+/g, ' '); 
     $.trim(text); 
     text = text.replace(/\d\.\s+|[a-z]\)\s+|•\s+|[A-Z]\.\s+|[IVX]+\.\s+/g, ''); 
     text = text.replace(/([0-9A-Za-z]+[.)]|•)\s+/g, ''); 
     var words = text.split(' '); 
     for(var i = 0; i < words.length; i++) { 
      $all.highlight(words[i]); // Will highlight the script with background color 
     } 
    } 
} 
+0

非常感谢您的回答。 – Exception