Javascript and regex in a loop with a var?

This has got me pulling out my hair, what little is left of it :smiley:

I have a need to ‘clean’ filenames from user input/upload of symbols. Everywhere there is a symbol I want to replace it with a dash ‘-’.

I will confess that I’m VERY green on regex’s. I know enough to get by on but this has definitely got me flustered.

My goal was to have an array of the symbols. Then use a for statement to iterate through that array and replace the symbols and then eventually return the cleansed filename.

I think my problem is with escaping symbols that mean something to regex like * or (

function cleanFileName(filename)
	var illegal_chars = new Array('`', '~', '!', '@', '#', '$', '*', '(', ')', '+', '%', '^', '&', '=', '_',  '[', '{', ']', '}', '|', ';', ':', "'", '"', ',', '<', '>', '/', '?', ' ');
	for (var i=0; i<illegal_chars.length; i++) 
		//var q = new RegExp('\\'+illegal_chars[i],"g");
		//var q = new RegExp(illegal_chars[i],"g");
		var q = illegal_chars[i];

		filename = filename.replace(/\\q/g, '-');

	return filename;	
	} // end cleanFileName function

I’ve now tried so many variations of this code my head is spinning… Any advice or guidance would be GREATLY appreciated.

Well, I think I’ve got my problem solved… figures… I work on the think for hours, finally post my issue… then 5 mins later I solve the problem. Does this happen to anybody other than me?? hmmm…

It looks like I needed to escape the escape symbol

var q = new RegExp(‘\\’+illegal_chars[i],“g”);