2013-08-23 82 views
1

有誰知道如何在IE8中完成這項工作?IE8正則表達式不起作用

var html = (function() {/* <!DOCTYPE html> <html> 
    <body> 
     <h1>Hello, world!</h1> 
    </body> </html>   
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1]; 

鉻返回這個(這是預期的答案)

<!DOCTYPE html> 
    <html> 
    <body> 
     <h1>Hello, world!</h1> 
    </body> 
    </html> 

但IE8不喜歡它,它返回

'/' expected 

我已經驗證了toString()部分IE8和它包含

"(function() {/* <!DOCTYPE html> <html> 
     <body> 
      <h1>Hello, world!</h1> 
     </body> </html>   
    */})" 

目標是提取註釋中的內容,因此可以在JavaScript中使用多行字符串而不添加任何字符。 因此,如果有人提出了另一個在IE8和Chrome中運行的正則表達式,那將會很棒。

+3

您在IE 8中遇到了什麼問題。製作一個人們可以看到的**演示**總是件好事。這樣你就可以更快更輕鬆地得到答案。 – iConnor

+0

這在Chrome中如何工作? – Hamish

+1

是的。你的預期產出是多少?你的實際產出是多少? – Andy

回答

0

應用於函數的toString方法不一定會返回與打印輸入完全一樣的源代碼。 MDN表示「toString反編譯函數,而返回的字符串包含函數關鍵字,參數列表,花括號和函數體的來源」。它也表明這是非標準和過時的。 ECMAScript標準有以下說:

15.3.4.2 Function.prototype.toString ()

An implementation-dependent representation of the function is returned. This representation has the syntax of a FunctionDeclaration. Note in particular that the use and placement of white space, line terminators, and semicolons within the representation String is implementation-dependent.

The toString function is not generic; it throws a TypeError exception if its this value is not a Function object. Therefore, it cannot be transferred to other kinds of objects for use as a method.

我毫不猶豫地說,所有的JS實現支持function.toString,但我知道沒有不的。但是它們的實施情況各不相同Chrome似乎會返回包括評論在內的完整源代碼,Firefox會刪除評論。

我和你的想法一樣,使用註釋來傳遞信息,但當我發現Firefox刪除它們時放棄了它。

所有這一切,因爲toString 返回註釋字符串那裏必須有問題與RE。不具有IE8可用於測試,我不能建議的最終解決,但你可以嘗試以下操作:

/\/\*([^]*?)\*\/\}$/ 

我已刪除了多餘[^] *在啓動和取得的捕獲[^] *非貪婪。 您的原始版本和我的Chrome瀏覽器都改變了一個版本。

+0

>> source.match(/ \/\ *([^] *?)\ * \/\} $ /) 「']'在正則表達式中預期' –

+1

嗯,Chrome沒有問題。嘗試用'[。\ n \ r]' – HBP

+0

source.match(/ \/\ *([。\ n \ r] *?)\ * \/\} $ /替換'[^]') = > null –