Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
123
rated 0 times [  124] [ 1]  / answers: 1 / hits: 17781  / 8 Years ago, fri, april 22, 2016, 12:00:00

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


More From » regex

 Answers
16

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 one RegExp from another) when the first argument is a RegExp and the second flags argument is present. A new RegExp 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.



[#62440] Wednesday, April 20, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jackelyn

Total Points: 303
Total Questions: 103
Total Answers: 102

Location: Turks and Caicos Islands
Member since Sun, Mar 7, 2021
3 Years ago
jackelyn questions
Thu, Apr 8, 21, 00:00, 3 Years ago
Sun, Feb 28, 21, 00:00, 3 Years ago
Mon, May 25, 20, 00:00, 4 Years ago
Thu, Apr 30, 20, 00:00, 4 Years ago
;