Javascript not recognizing new line - javascript

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>.

Related

Adding Line Numbers To Pre-formatted Text

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;

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.

HTML5 Href "sms" content with break line tag?

I want to use html link href to text message(sms) in android smart phone.But i try want the breakline in my message content.I have to display my message in messengers like below
"adgsd
sdgsf
asdfdf"
I try use "< br >","< br/ >","/n","/r" also cant break line.
Any Idea?Below is sample code with replace the < br > to other tag.
link = "smsto:" + "601" + "?body=" + document.getElementById("DetailContent").innerHTML.replace(/<br>/g, '\n');
document.getElementById("smsDetailLink1").setAttribute("href", link);
"%0D%0A"
with this format can get break line.
For anyone wondering, the answers given above are just the hex ASCII codes for the DOS/Windows line ending CR-LF (\r\n), i.e. carriage return and line feed. A lot of you probably knew that, some may not.

HTML textarea ignores 1st new line character, why?

Could you explain why this:
<script type="text/javascript">
document.write("<textarea cols='10' rows='10'>" + "\nhello\nbabe\n" + "</textarea>");
</script>
renders a textarea with one new line at the bottom, but NO new line at the top?
Tested IE8, FF11, Safari 5.1, Chrome 24
And it's not a JS issue, even when you write HTML in page you get the same result, i.e.
<textarea cols='10' rows='10'>
hello
babe
</textarea>
The 1st new line is still missing!!!
I need to add another new line at the top in order to show one:
document.write("<textarea cols='10' rows='10'>" + "\n\nhello\nbabe\n" + "</textarea>");
When writing inside of XHTML use proper entities.
<textarea>
hello</textarea>
If a text node begins with white space (space, new line) it will be ignored by HTML parsers. Encoding the new line into a proper HTML entity forces the parser to acknowledge it.
== carriage return
Answering the question "Why". This is specified in HTML 5 specification in the chapter that describes how DOM tree is created from tags found in a HTML document.
In the current HTML 5 living standard it is "12.2 Parsing HTML documents" > "12.2.6 Tree construction" > "12.2.6.4 The rules for parsing tokens in HTML content" > "12.2.6.4.7 The "in body" insertion mode".
(In HTML 5.2 the same section is numbered 8.2.5.4.7).
Scroll down for item "A start tag whose tag name is "textarea""
A start tag whose tag name is "textarea"
Run these steps:
1. Insert an HTML element for the token.
2. If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.)
3. Switch the tokenizer to the RCDATA state.
...
The algorithm deals with LF characters only, because CR characters are handled earlier.
(Historically, looking into obsolete HTML 4.01 specification:
Its Chapter 17.7 "The TEXTAREA element" has an example that shows that text content for a textarea starts from a new line.
Appendix B.3.1 Line breaks (informative) explains that such behaviour originates from SGML.)
A line break character before </textarea> end tag is not ignored nowadays, in HTML 5.
If possible, change your code to have the textarea pre-defined as html, then write the string like this instead:
HTML:
<textarea cols='10' rows='10' id='test'></textarea>
Script:
document.getElementById('test').innerHTML = '\nhello\nbabe\n';
That should preserve white-space. Optionally you can add a css rule:
textarea {
white-space:pre;
}
A fiddle to play with:
http://jsfiddle.net/RFLwH/1/
Update:
OP tested in IE8 which this does not work - it appear to be a limitation/bug with this browser. IE8 do actually use CR+LF if you manually insert a line-feed at the top, but when set programmatic this is completely ignored by the browser.
Add this to the html to do a test:
<span onclick="this.innerHTML = escape(document.getElementById('test').innerHTML);">
Get textarea content
</span>
You can see the string returned is:
%0D%0Ahello%20babe%20
meaning the CR+LF is there (the other line-feeds are converted to spaces - but inserting a space at the beginning does not help either). I guess there is nothing you can do about this behavior; the browser is obsolete (but unfortunately still widely used so this can be a problem for those users if this is essential).
Add a whitespace before the first "\n" like this :
<script type="text/javascript">
document.write("<textarea cols='10' rows='10'>" + " \nhello\nbabe\n" + "</textarea>");
</script>
or
<textarea cols='10' rows='10'> <!-- whitespace here -->
hello
babe
</textarea>
otherwise it won't work.
Update:
Later in your server side, you can remove the first whitespace by doing
$str = ltrim ($str,' ');
or
$str2 = substr($str, 4);
if it is PHP.
It should be a \n\r at the top:
document.write("<textarea cols='10' rows='10'>" + "\n\rhello\nbabe\n" + "</textarea>");
jsbin
Finally i finished with this server-side solution:
to double leading(only first!) nl symbol before output it in textarea:
if(str_startswith("\r\n",$value))
{
$value = "\r\n".$value;
}elseif(str_startswith("\n",$value))
{
$value = "\n".$value;
}elseif(str_startswith("\r",$value))
{
$value = "\r".$value;
}
function str_startswith($start, $string)
{
if(mb_strlen($start)>mb_strlen($string))
return FALSE;
return (mb_substr($string, 0,mb_strlen($start))==$start);
}

string search in body.html() not working

Hi here is my total work to search a string in HTML and highlight it if it is found in document:
The problem is here
var SearchItems = text.split(/\r\n|\r|\n/);
var replaced = body.html();
for(var i=0;i<SearchItems.length;i++)
{
var tempRep= '<span class="highlight" style="background-color: yellow">';
tempRep = tempRep + SearchItems[i];
tempRep = tempRep + '</span>';
replaced = replaced.replace(SearchItems[i],tempRep); // It is trying to match along with html tags...
// As the <b> tags will not be there in search text, it is not matching...
}
$("body").html(replaced);
The HTML I'm using is as follows;
<div>
The clipboardData object is reserved for editing actions performed through the Edit menu, shortcut menus, and shortcut keys. It transfers information using the system clipboard, and retains it until data from the next editing operation replace s it. This form of data transfer is particularly suited to multiple pastes of the same data.
<br><br>
This object is available in script as of <b>Microsoft Internet Explorer 5.</b>
</div>
<div class='b'></div>
If I search for a page which is pure or without any html tags it will match. However, if I have any tags in HTML this will not work.. Because I am taking body html() text as the target text. It is exactly trying to match along with html tags..
In fiddle second paragraph will not match.
First of all, to ignore the HTML tags of the element to look within, use the .text() method.
Secondly, in your fiddle, it wasn't working because you weren't calling the SearchQueue function on load.
Try this amended fiddle

Categories