Javascript Regular Expression failing in IE, but working in Chrome & Edge
Solution 1
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.
Solution 2
Double escape \\
and a string representation should do it:
filename = filename.replaceAll(new RegExp('[^a-zA-Z0-9_\\-&.]+', 'g'), '_');
Related videos on Youtube
Matt
Updated on September 16, 2022Comments
-
Matt over 1 year
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
-
sp00m about 8 yearsSide question: what is the purpose of your
replaceAll
function, as it is just calling standardreplace
one?
-
-
Alan Moore about 8 yearsThose are actually single quotes, but yeah, I was going to suggest the same thing. Passing a regex literal to the RegExp constructor has always been technically incorrect; maybe IE 11 is the only one that enforces that rule.
-
Wiktor Stribiżew about 8 yearsThere is no need escaping the hyphen if placed at the end of the character class.
-
Tito Leiva about 5 yearsI solved it changing the mode from
gs
tog
instead.