简体   繁体   中英

Awkward escape characters

Whilst trying to console.log a string I've run into a rather annoying issue. I store the string 2^{\\\\frac{1}{2}}x=1 in a Node.js database yet when outputting it gives 2^{rac{1}{2}}x=1 . I predicted issues with the \\f escape character and as such I added the 2nd \\ to escape that problem. But the issue remains and I'm stumped as to how to fix it.

When looking at the Mongoose debug output it clearly stores it in the data correctly: 在此处输入图片说明

It is assigned like this:

contentHolder = "<%= testData.topics[i].questions[t].methods[p][0].content %>";

Yet when I run this line:

console.log(contentHolder);

I get this:

2^{rac{1}{2}}x=1

If you view the 'source' in your web browser I imagine you'll see that this:

contentHolder = "<%= testData.topics[i].questions[t].methods[p][0].content %>";

will have generated this:

contentHolder = "2^{\frac{1}{2}}x=1";

When that JS string literal is interpreted the \\f will be converted into a form feed character, which obviously isn't what you want.

There are various ways you could try to fix the escaping but I think I'd just use JSON.stringify :

contentHolder = <%- JSON.stringify(testData.topics[i].questions[t].methods[p][0].content) %>;

There may be some edge cases where this still doesn't quite get the escaping right but unless you're outputting values entered by users that's unlikely to be a problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM