Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
844 views
in Technique[技术] by (71.8m points)

regex - Javascript Regular Expression failing in IE, but working in 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'), '_');

Desired output is

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

Any help would be greatly appreciated.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...