Putting regular expressions in strings

I am trying to dynamically create a javascript file B using a javascript file A (written in Node.js) by writing a string from A to a .js file B. I want to use regular expressions in the javascript file B. This requires me to put the regex functions for B in a string in A. However, whenever I use the backslash (escape character), file A interprets the regex function immediately, instead of treating it as a string.

Some code to help in understanding my problem:

var mongodata = "Some String with square and curly brackets ]}{]]},]},}{}{{}},{[[][,][,";
mongodata = 'var mongodata = ' + mongodata + ';\n function setData(){mongodata = mongodata.replace(/\[ /g,"").replace(/\] \},/g,"</td></tr>").replace(/\] \}/g,"</td></tr>"); document.getElementById("mongodata").innerHTML = mongodata;}';

That mongodata string is intended to be used as the content of a dynamically created .js file.

I understand the wording of this question may be slightly confusing. Please let me know if more clarification is needed.

In your string, just like the \n character, all the other backslashed expressions are being evaluated, so you must escape the backslashes. In other words, write a RegExp that outputs a RegExp. The proper way of escaping the backslashes themselves is \\\ , but you might need to escape other characters as well to prevent their evaluation.

Perhaps I'm misunderstanding your problem, but maybe put the string being assigned to mongodata in escaped quotes:

var mongodata = "\'Some String with square and curly brackets ]}{]]},]},}{}{{}},{[[][,][,\'";

Bit of a lottery this one. I too don't quite understand your question.

You can escape all of the RegEx special characters (. * ? [ ] Etc). You can also dynamically create RegEx operators using:

var objRegEx = new RegExp( pattern, modifiers );

Like I say, lottery... stab in the dark...