1

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.

3 Answers 3

1

you may use the following to replace your line breaks with <br /> tags an then set the HTML:

return $('<div />').html(stringToDecode.replace(/\n/, '&lt;br /&gt;')).text();
Sign up to request clarification or add additional context in comments.

2 Comments

I improved your solution: var tempTagName = 'LineBreak'; var decodedString = $('<div />').html(stringToDecode.replace(/\n/g, '&lt;' + tempTagName + "/&gt;\r\n")).text(); return decodedString.replaceAll('<' + tempTagName + '/>', '\r\n');
The line break Regexp should be /(\r\n|\n|\r)/gm textfixer.com/tutorials/javascript-line-breaks.php
1
function decodeString(stringToDecode) {
    return stringToDecode ? $('<div />').html(stringToDecode.replace(/[\n\r]/g, "<br> \r\n")).text() : ""
}

Comments

-1

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.