javascript正则表达式在IE中失败,但在Chrome&边缘 [英] Javascript Regular Expression failing in IE, but working in Chrome & Edge

查看:42
本文介绍了javascript正则表达式在IE中失败,但在Chrome&边缘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用javascript中的正则表达式替换文件名中的非法字符,但在IE 11中,它始终显示正则表达式语法错误".相同的代码在Chrome和Edge中可以正常工作.

Im trying to replace illegal characters from a filename using a regular expression in javascript but it keeps falling over in IE 11 with 'Syntax error in regular expression'. The same code works fine in Chrome and Edge.

String.prototype.replaceAll = function (search, replacement) {
     var target = this;
     return target.replace(search, replacement);
};

var filename = 'test+&+this+again.2016.txt';

filename = filename.replaceAll(new RegExp(/[^a-zA-Z0-9_\-&.]+/, 'g'), '_');

所需的输出是

filename = 'test_&_this_again.2016.txt';

任何帮助将不胜感激.

谢谢

推荐答案

关键是,您看到的并非所有浏览器都支持接受正则表达式文字对象的 RegExp 构造函数.使用这样的通用代码:

The point is that RegExp constructor accepting the regex literal object is not supported in all browsers as you see. Use a common code like this:

filename = 'test+&+this+again.2016.txt'; 
filename = filename.replace(/[^a-zA-Z0-9_&.-]+/g, '_');
document.body.innerHTML = filename;

使其始终如一地工作.当浏览器开始符合ES6时,在构造函数中使用regex文字对象不会有任何麻烦(

For it to work consistently. When the browsers start complying with the ES6, there won't be any trouble using the regex literal object inside the constructor (source: MDN):

从ECMAScript 6开始,新RegExp(/ab + c/,'i')不再引发 TypeError ("can从另一个构造一个 RegExp 时不提供标志"),当第一个参数是 RegExp 且第二个标志参数存在时.而是根据参数创建一个新的 RegExp .

Starting with ECMAScript 6, new RegExp(/ab+c/, 'i') no longer throws a TypeError ("can't supply flags when constructing one RegExp from another") when the first argument is a RegExp and the second flags argument is present. A new RegExp from the arguments is created instead.

此外,由于该模式不是动态构建的,因此我建议使用 regex文字表示法.这是来自 MDN 的建议:

Also, I suggest using a regex literal notation since the pattern is not built dynamically. Here is the recommendation from MDN:

文字表达式在计算表达式时提供正则表达式的编译.当正则表达式保持不变时,请使用文字符号.

The literal notation provides compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant...

正则表达式对象的构造函数,例如新的 RegExp('ab + c'),提供了正则表达式的运行时编译.当您知道正则表达式模式将要更改,或者您不知道该模式并从其他来源(例如用户输入)获取该模式时,请使用构造函数.

The constructor of the regular expression object, for example, new RegExp('ab+c'), provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

这篇关于javascript正则表达式在IE中失败,但在Chrome&边缘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆