Reputation: 26311
I have a string:
<Grid><Description>LINE 1
LINE 2
LINE 3
LINE 4
</Description><</Grid>
I need it to be decoded with line breaks. I found solution:
function decodeString(stringToDecode) {
if (!stringToDecode) {
return stringToDecode;
}
return $('<div />').html(stringToDecode).text();
}
But it makes single line and replaces all the line breaks with spaces.
Upvotes: 1
Views: 1527
Reputation: 58601
function decodeString(stringToDecode) {
return stringToDecode ? $('<div />').html(stringToDecode.replace(/[\n\r]/g, "<br> \r\n")).text() : ""
}
Upvotes: 1
Reputation: 20240
you may use the following to replace your line breaks with <br />
tags an then set the HTML:
return $('<div />').html(stringToDecode.replace(/\n/, '<br />')).text();
Upvotes: 1
Reputation: 21834
Your sample has CR/LF - but that is not a line break in HTML. You need to replace it with a valid HTML line break ie the < br > tag.
Your function has a strange if statement that does not make much sense. Why return stringToDecode when you've just proven it is null? Also, $('<div />').html(stringToDecode).text()
will not do anything helpful.
Try something like this:
function decodeString(stringToDecode) {
if (!stringToDecode) {
return "";
}
var regX = /\\n/g;
var replaceString = '<br> \\n';
return stringToDecode.replace(regX, replaceString);
}
Upvotes: -1