1

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.

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! You were very close. You would actually need a set of three backslashes (`\\`). But thanks for pushing me in the right direction. +1 +Accept.
Glad to help, and sorry for the misleading, I'm not an expert of RegExp. Feel free to edit my answer!!!
0

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 ]}{]]},]},}{}{{}},{[[][,][,\'";

Comments

0

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...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.