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.
Related
I have a body of text that I show in a web page within some <pre> tags. I would like to add a column to the left of this text body to show the line number of the text.
The body of text is retrieved by using [PHP] file_get_contents() so I am just echo-ing a string within the <pre> tags.
I imagine this can be accomplished with JavaScript but I have yet to find a solution.
Solutions I have seen on here usually use a library or CSS. The CSS method would be great but this method seems to require that each line of the body text have its own corresponding tag (eg <p> or <span>).
// Example of CSS Solution
p:not(:first-child):before {
counter-increment: custom-counter+1;
content: counter(custom-counter)". ";
display: table-cell;
}
p:first-child:before {
display: table-cell;
content: '1. '
}
I would like to avoid having to create a DOM element (before load) line by line. That said, if that is the best solution I simply want to know the "preferred" way to go about this.
How could I accomplish this using JavaScript / jQuery?
One simple solution would be to split the string on "\n" with javascript to get each line append the line numbers then re-join them together. This will only work if you are using <pre> tags where newlines are literal newlines.
JsFiddle
let text = document.getElementById("test").innerHTML;
let lines = text.split("\n");
for (let i=0;i<lines.length;i++) {
lines[i] = (i+1)+" "+lines[i];
}
text = lines.join("\n");
document.getElementById("test").innerHTML = text;
I am posting some details into my Nodejs backend using ajax request and creating a string with multiple lines. To do this I am doing something like:
changeString = req.body.Change1 + '\n'
changeString = changeString + req.body.Change2 + '\n'
changeString = changeString + req.boyd.Change3 + '\n'
....
After this I am inserting this field to my database. This is working perfectly fine and I can go in the database and copy the field value into a notepad and see the line changes:
sdsdsds
sdsdsds
asdasdsadasdasdas
In another page of my website I am pulling the details from the same field and adding it to a table but instead of new lines I am getting
sdsdsds sdsdsds asdasdsadasdasdas
To add to my table I am doing
`<tr>
<td>${item.Name}</td>
<td>${item.Time}</td>
<td>${item.Description}</td>
</tr>`
If I console.log the item description I can see the line changes
The line changes somehow disappear when I add in the HTML.
Perhaps try to CSS mark the element that contains line break characters with
white-space: pre-line
or with
white-space: pre-wrap;
For example like this:
<span style="white-space: pre-line">${item_here}</span>
HTML parser will ignore whitespace characters (including \n newline) in the source code, so you can use <br/> tag to create a newline or render your strings inside a <pre> /*sometex*/ </pre>.
here is my code:
function myFunction() {
var str = " Hello World ";
document.getElementById("demo").innerHTML=str;
alert(str);
}
<p id="demo"></p>
<button onclick="myFunction()">Try it</button>
While the Alert window outputs the string as it is i.e with spaces, the p element receives the string in trimmed form i.e with no spaces?
In HTML, regular whitespace chararacters between tags are not interpreted as whitespaces to render by the browser.
Declaring one or multiple of them will give the same result: they are collapsed and are rendered as a single space.
To render multiple whitespaces, you have two ways :
in plain HTML use the entity ( , or non-breaking space)
in CSS, use the white-space property: white-space: pre-wrap;
pre-wrap
Sequences of whitespace are preserved. Lines are broken at newline
characters, at <br>, and as necessary to fill line boxes.
Source: MDN’s article on white-space
It is not the innerHTML. Real culprit is Browser. You cannot see the spaces in the browser directly with string literals as all browsers will always truncate spaces in HTML. You have use   to see them.
While browser processing your html, it follows some rules.
Here is the 16.6.1 The 'white-space' processing model
If 'white-space' is set to 'normal', 'nowrap', or 'pre-line',
every tab (U+0009) is converted to a space (U+0020)
any space (U+0020) following another space (U+0020) — even a space before the inline, if that space also has 'white-space' set to 'normal', 'nowrap' or 'pre-line' — is removed.
If you would like to see those whitespaces, you could use CSS's white-space property and set it to pre (which breaks only on given line-breaks) or pre-wrap (which breaks whenever necessary).
However are you sure, that you really want to do positioning of text in HTML? Is there any reason that you leave the spaces and instead use padding on your element to shift its content?
It depends on the browser.
If you wanna be sure to have the space, do this:
function myFunction() {
var str = " Hello World ";
document.getElementById("demo").innerHTML=" " + str + " ";
alert(str);
}
myFunction();
This is my small jquery script where I append data that I receive.
$.get('HelloWorld', {'data' : data}, function(newLogs) {
$('#logsid').append(newLogs);
$('#logsid').scrollTop($('#logsid')[0].scrollHeight);
});
By default, HTML renders newlines as spaces (and multiple whitespace is collapsed to one space). Add this rule to your stylesheet to preserve whitespace...
#logsid {
white-space: pre;
}
Or you can do this in jQuery...
$('#logsid').css("white-space", "pre");
You can also achieve this by changing logsid to be a <pre> element.
I have the following code:
var stringDisplay = "Hello\nWorld";
$("#meaning").text(stringDisplay);
It is displaying \n instead of a newline.
The output is showing up as Hello\nWorld.
I used <br> tag also in place of \n, but it's still not working.
You will have to use both .html() and replace the newline:
var escaped = $('<div>').text(stringDisplay).text();
$('#meaning').html(escaped.replace(/\n/g, '<br />'));
An alternative would be to style the element:
white-space: pre-wrap;
How about this
$('meaning').html('line1<br>line2');