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
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;
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):
Starting with ECMAScript 6,
new RegExp(/ab+c/, 'i')
no longer throws a TypeError ("can't supply flags when constructing oneRegExp
from another") when the first argument is aRegExp
and the second flags argument is present. A newRegExp
from the arguments is created instead.
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...
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.
Double escape \\
and a string representation should do it:
filename = filename.replaceAll(new RegExp('[^a-zA-Z0-9_\\-&.]+', 'g'), '_');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With