I have an array in js that is generated by values from database. My problem is that some values in database have line breaks, so my array in console look like this:
let arr=[{
"Lorem
ipsum dolor
amet"
},{...
];
(And it isn’t working because it isn’t at the same line)
At the same time in source:
let arr=[{
"Lorem \n ipsum dolor \n amet"
},{...
];
How can I display it in html keeping the line breaks?
I mean I want display in html with line breaks:
Lorem
ipsum dolor
ame
PHP interprets variables in strings when enclosed in double quotation marks. It also interprets control characters that are enclosed in double quotation marks.
Can you make them single quotation marks? escape the escape?
That’s not valid syntax; you’re using "Lorem \n ipsum dolor \n amet" as the key for an object literal here, but missing the value assignment. Did you mean something like this?
let arr=[
"Lorem \n ipsum dolor \n amet",
// ...
];
BTW if you want to include the string as-is you might use the template syntax (using backticks instead of quotes):
let arr=[
`Lorem
ipsum dolor
amet`,
// ...
];
(This syntax is not supported in IE though.)
PS: As you see, generating JS dynamically can get messy pretty quickly. The canonical way would be to just encode the data as JSON, e.g. using PHP:
Okay I think it’s enough to cope with it for me
My array in real looks like this, but I change it for ease: let arr=[{".."}, {".."}];
But it doesn’t matter.
Thank you very much for help.
Right, let’s throw away the idea of the array for the moment, because you’ll have this problem with a single entry, let alone an array.
You have a string. That string contains line breaks. You’re trying to put the string into an object.
Let’s assume for the moment that you are sanely creating an object.
{ "title":"Gone with the
Wind"}
obviously doesnt work.
Options.
1: replace the line breaks with a non-breaking character.
2: replace the line breaks with an HTML line break.
3: replace the line breaks with an escaped break.
PHP:
$string = "My string
has line breaks
PHP Doesnt Care.";
//1
echo "{\"title\":\"".str_replace("\n","_",$string)."\"}";
// Returns: {"title": "My string_has line breaks_PHP Doesnt Care."}
//2
echo "{\"title\":\"".str_replace("\n","<br>",$string)."\"}";
// Returns: {"title": "My string<br>has line breaks<br>PHP Doesnt Care."}
//3
echo "{\"title\":\"".str_replace("\n","\\n",$string)."\"}";
// Returns: {"title": "My string\nhas line breaks\nPHP Doesnt Care."}
As m3g4 mentions however, json_encoding the data array will be the quicker, easier method. (I believe json_encode goes with option 3 in this case?)