简体   繁体   中英

display string with markup in javascript

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?

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> 

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

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

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

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