2013-08-23 136 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 –