简体   繁体   中英

JavaScript and array of strings containing \r and / or \n characters

I have a dynamically generated array from a database. Basically it's an array of objects which PHP prints out to the page in the section.

The final output is somrthing like: var arPersons=[{'name':'aaa',description:'2-3 lines text in 300px wide div'},{etc}];

Now there seems to be a problem with this array when newline caracters ( \\n ) or carriage return characters ( \\r ) appear in the description text as that is written from a CMS.

How can I solve this? What I currently do is str_replace(array("\\r\\n","\\r","\\n"),"",$description); , where $description is changed for each element in the loop.

I am unsure this is the best way. Is there a way I can tell the JS code not to mess up when there are \\n and \\r characters somehow? Should it still be done in PHP rather than JS?

By mess up I mean any code after that array stops being executed. mess up我的意思是该数组停止执行后的任何代码。 If I remove description entirely or just the \\n and \\r characters it will work (in both cases).

Thank you.

The best way is to use json_encode() from the start. It fully escapes everything for output to Javascript.

http://php.net/json-encode

PHP has a nl2br() function that takes newlines in a string and turns them into <br /> s. You could run your string through that if you are wanting to keep the formatting. The sub-par docs for nl2br are here

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