2017-05-05 64 views
0

我有以下功能對單個字符串inputHtml執行多個替換操作。它運作良好,但需要很長時間。是否可以通過組合它們來加速它?Javascript:在單個字符串中執行多個「替換」

/* Receives HTML code and returns the plain text contained in the HTML code */ 
function decodeHtml(inputHtml) { 
    const commentsRemoved = inputHtml.replace(/<!--[\s\S]*?-->/gm, ''); 
    const linebreaksAdded = commentsRemoved.replace(/<br>/gm, '\n'); 
    const tagsRemoved = linebreaksAdded.replace(/<(?:.|\n)*?>/gm, ''); 
    const linebreaksRemoved = tagsRemoved.replace(/^\s*[\r\n]/gm, ''); 
    const plainText = entities.decode(linebreaksRemoved); 

    return plainText; 
} 
+0

這當然有可能!你有什麼嘗試? –

+2

'(?:。| \ n)*?'是真正減慢速度的原因。已經將它固定爲'[\ s \ S] *?'會給你一些提升。 –

+0

你使用nodejs嗎? –

回答

1

因爲你正在做一些置換與換行,使之成爲一個單一的
通正則表達式,你必須做一個小的功能相結合。

Regex的解釋

(<!-- [\s\S]*? -->)   # (1), return '' 
| 
    (?:       # Blank lines, simulate^multiline 
     (\r? \n)     # (2), return $2 
     | (       # (3 start) 
       (\r?)      # (4), return $4 + '\n' 
       <br> 
     )        # (3 end) 
    ) 
    (?: \s | <br> | <!-- [\s\S]*? -->)* 
    \r? 
    (?: \n | <br>) 
| 
    (<br>)      # (5), return '\n' 
| 
    (< [\s\S]*? >)    # (6), return '' 

JS代碼

var input = 'here<br> <br> <br> <br><!-- <br> --> <br><br><br><br>and here<br>and there '; 
 

 
var output = input.replace(/(<!--[\s\S]*?-->)|(?:(\r?\n)|((\r?)<br>))(?:\s|<br>|<!--[\s\S]*?-->)*\r?(?:\n|<br>)|(<br>)|(<[\s\S]*?>)/g, 
 
    function(m,p1,p2,p3,p4,p5,p6) { 
 
     if (p1 || p6) 
 
      return ""; 
 
     // 
 
     if (p2) 
 
      return p2; 
 
     if (p3) 
 
      return p4 + "\n"; 
 
     // 
 
     if (p5) 
 
      return "\n"; 
 
     }); 
 
     
 
console.log(output);

輸入

here<br> <br> <br> <br><!-- <br> --> <br><br><br><br>and here<br>and there 

輸出

here 
and here 
and there 
相關問題