简体   繁体   中英

String with new line escape characters breaks Javascript script

I have a Javascript script that uses EL and tld files to get some text from the database: Code that follows is the relevant line:

var deText = unescape("${smfn:getText('HelpTextDe')}");

The problem is that the text in the database can contain new line escape characters like this:

German+text%0D%0AGerman+next+line

and naturally javascript function breaks down. The following image shows the error that I get in console:

在此处输入图片说明

I have also tried without unescape method (actually, that was my first version, I later added unescape hoping that it will solve my problem), but it was the same.

Is there a way to solve this without preventing such entries to the database?

NOTE: When answering please keep in mind that my knowledge of Javascript is very limited.

Any help is appreciated. Thanks in advance!

I'm not sure exactly what server software is doing the conversion, so i can't provide code, only a strategy.

JavaScript doesn't allow newlines in string literals like that, as you might have figured out. To get around that, before sending it to the client, you'll need to replace newlines with a literal \\n escape code.

You also shouldn't need unescape() now.

As i said, i leave it up to you to actually implement this.

If the database actually has escaped %0D and %0A characters, this will work perfectly fine. Try running this code: document.write('<pre>' + unescape('a%0Db%0Ac') + '</pre>');

It works. (Note that without the <pre> tag, the newlines will appear to be spaces when the browser renders them. If you view the page in Firebug / Chrome: Inspect element, you will see the newlines correctly.)

The problem is that the database has UNESCAPED newlines in it and Javascript thinks your string is terminating at the end of the line. If you change the database to actually contain the %0D%0A characters, this will work fine.

Also, I really hope that the text you're rendering from the database wasn't entered by a user. That is a huge security problem unless you scrub it.

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