Javascript Regular Expression does not work in IE, but works in Chrome & Edge

I am trying to replace illegal characters from a file name using regular expression in javascript, but it continues to fall 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'), '_');

Required conclusion

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

Any help would be greatly appreciated.

thank

+4
source share
2 answers

The thing is, a constructor RegExpthat takes a literal regular expression object is not supported in all browsers, as you can see. Use the generic code as follows:

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

. ES6, (source: MDN):

ECMAScript 6, new RegExp(/ab+c/, 'i') TypeError ( " RegExp " ), RegExp flags. RegExp .

, , . MDN:

. , ...

, new RegExp('ab+c'), . , , , , .

+6

escape \\, :

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

All Articles