Chrome中出错,但Firefox没有

时间:2013-08-16 06:40:49

标签: javascript google-chrome

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>a demo page</title>
</head>

<body>
<script>
var formatNum=function(num)
   {
        if(!/^(\+|-)?\d+(\.\d+)?$/.test(num)){
            return num;
        }
    var re = new RegExp().compile("(\\d)(\\d{3})(,|\\.|$)");
    num += "";
    while(re.test(num))
        num = num.replace(re, "$1,$2$3")
    return num;
}
alert(formatNum(1000000));
</script>
</body>
</html>

我使用这些代码看起来像 1,000,000 这样的代码在firefox中运行良好,但在chrome中不起作用

这里是chrome中显示的错误未捕获的TypeError:无法调用未定义的方法'test' 我该如何解决这个错误

3 个答案:

答案 0 :(得分:0)

不推荐使用RegExp().compile()方法。

为什么不使用这样的正则表达式 - :

var regexp = new RegExp("(\\d)(\\d{3})(,|\\.|$)");

答案 1 :(得分:0)

试试这个

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>a demo page</title>
</head>

<body>
<script>
var formatNum=function(num)
   {
        if(!/^(\+|-)?\d+(\.\d+)?$/.test(num)){
            return num;
        }
    var re = new RegExp();
    re.compile("(\\d)(\\d{3})(,|\\.|$)");
    num += "";
    while(re.test(num))
        num = num.replace(re, "$1,$2$3")
    return num;
}
alert(formatNum(1000000));
</script>
</body>
</html>

原因是chrome在调用compile()时没有返回对已编译的RegExp对象的引用。

因此,此行var re = new RegExp().compile("(\\d)(\\d{3})(,|\\.|$)");将无效,而需要遵循不太灵活的版本。

 var re = new RegExp();
 re.compile("(\\d)(\\d{3})(,|\\.|$)");

答案 2 :(得分:0)

它已被弃用,也不在firefox中运行。也许你的版本是旧版本。

Deprecated and obsolete features

使用@Raoul的建议。

相关问题