0

I have a string with the following format :

" Data\r\n  more data <DIV> "

I want to display this string exactly including the leading spaces and line breaks.

" Data
   more data <DIV> "

I am currently using jquery to display this like

$("<small class='text-success'></small>").text(theString)

This nicely encodes any HTML elements to display but doesn't work for the leading spaces or line breaks.

I tried replacing the spaces with non breaking spaces but then the text method also encodes that too.

Is there a way to do this without manually encoding the whole string?

3 Answers 3

1

This nicely encodes any HTML elements to display but doesn't work for the leading spaces or line breaks.

To do that, you'd want to use the white-space CSS property with the value pre, preline, or pre-wrap (but probably just pre). Ideally, do that by giving it a class you apply the styling to:

CSS:

.preformatted {
    white-space: pre;
}

and then

$("<small class='text-success preformatted'></small>").text(theString)

Example:

var theString = " Data\r\n  more data <DIV> ";
$("<small class='text-success preformatted'></small>").text(theString).appendTo(document.body);
.preformatted {
  white-space: pre;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

But if necessary, you can do it inline:

$("<small class='text-success'></small>").css("white-space", "pre").text(theString)

Example:

var theString = " Data\r\n  more data <DIV> ";
$("<small class='text-success'></small>").css("white-space", "pre").text(theString).appendTo(document.body);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

This is spot on, I changed the small element to a pre and didn't need the white-space property
0

You can use template literals to use exact strings as it is

var string= `Data
             more data <DIV>`;

Comments

0

You can try replace "\r\n" with "<br/>". That should prolly work.

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.