Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
847 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 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...