what's the different between <br> and \n as line break - javascript

I just finished a very simple assignment from my class. The part of the wrong code of script I wrote is like this:
alert("The circumference of a circle with this radius is " + circum +
"<br>" + "The area of a circle with this radius is " + area + "\n" +
"The surface area of a sphere with this radius is " + surarea + "\n" +
"The volume of a sphere with this radius is " + volume + "\n");
I have tried both <br> and \n in this part of code, and I am pretty sure that other parts are all right since I have tested them.
I was just wondering why the <br> doesn't work for me on my program. The example that the teacher gave us seems working fine. But he also told us that <br> should be used in HTML while \n is used in JS.
Thank you very much.

\n is a linebreak character. It is interpreted like that by the JS compiler. The HTML parsers on the other hand treat it as a normal string.
<br> in html is a tag to introduce a line break. In JS strings, this is treated as a normal string.

\n is a new line feed within the context of plain text
while <br>
is line break within the context of HTML

The <br> or <br /> tag is an HTML element that will display everything after this <br> or <br /> by starting from new line when rendered in browser while the \n is used to jump to next line in the source code or the output prompt in standard output.

<br> and <br /> are HTML and XHTML tags, while \n is a newline in code.

Related

How to put linebreaks on dynamically generated javascript code

Working on ASP.net website. In my webpage I'm dynamically writing some javascript in the code-behind code. How can I put linebreaks at certain points so that if I do a 'view source' of the page it is more readable? Right now all the dynamic js code is one one line.
I've tried appending <BR/> but that doesn't seem to work.
Thanks!
<br /> is html element which will not help you at this point. you can use Environment.NewLine to add these line-breaks: example code will be like the following:
StringBuilder strBuilderJS = new StringBuilder();
strBuilderJS.Append("<script language='javascript' type='text/javascript'>" + Environment.NewLine +
"$(WireEvents_" + this.ID + ");" + Environment.NewLine +
"function WireEvents_" + this.ID + "(){" + Environment.NewLine +
" alert('stuff');");
strBuilderJS.Append(Environment.NewLine + "}</script>");
If you're using Response.Write(), you can use \r\n to add a newline in your HTML output.
Example:
Response.Write("<div>\r\nThis is my text.\r\n</div>"
This will appear in the HTML as:
<div>
This is my text.
</div>

<br> is removed when I alert() the content of PRE tag

I want to show the content of this <pre> tag using alert():
<pre> This is the IRNIC Whois server v1.6.2.<br> Available on web at http://whois.nic.ir/<br> Find the terms and conditions of use on http://www.nic.ir/<br> <br> This server uses UTF-8 as the encoding for requests and responses.<br><br> NOTE: This output has been filtered.<br><br> Information related to 'shirzadi.ir'<br><br><br>domain: shirzadi.ir<br>ascii: shirzadi.ir<br>remarks: (Domain Holder) Ehsan Shirzadi<br>remarks: (Domain Holder Address) Ferdowsi Blv , Mahdi 13 ST, Mashhad, Khorasan razavi, IR<br>holder-c: es372-irnic<br>admin-c: es372-irnic<br>tech-c: to52-irnic<br>bill-c: to52-irnic<br>nserver: wres1.irpowerweb.com<br>nserver: wres2.irpowerweb.com<br>last-updated: 2014-01-16<br>expire-date: 2017-10-08<br>source: IRNIC # Filtered<br><br>nic-hdl: es372-irnic<br>person: Ehsan Shirzadi<br>e-mail: ehsan.shirzadi#gmail.com<br>address: Ferdowsi Blv , Mahdi 13 ST, Mashhad, Khorasan razavi, IR<br>phone: +985117688851<br>fax-no: +989155066372<br>source: IRNIC # Filtered<br><br>nic-hdl: to52-irnic<br>org: Fanavarie Etelaate Towseye Saman (Mihannic)<br>e-mail: sales#mihannic.com<br>source: IRNIC # Filtered<br><br></pre>
when I read this content using xx = $('pre').text() and then alert(xx), the is no <br> but when I hard code this content in a variable and alert() I can see them. What is the problem here? finally I want to split the contents by <br>
Try $('pre').html() instead of text(). This should preserve < br > as well as other tags / html entities.
Edit
For completeness, as gillesc said, < br > and other tags will be stripped in alert() (since it does not support inner html). Therefore combination of .html() and replace method is required. Newline can be replaced by \n. Full code would look like this:
xx = $('pre').html().replace(/<br>/g, "\n");
alert(xx);
text() will strip the tags out so use html() instead but alert doesn't support tags so you will need to convert your <br/> before sending it to laert
See this post on how to do just that.
HTML Tags in Javascript Alert() method
Using text() keeps only the inner text, not the HTML markup.
Use html() and eventually replace each captured <br /> by the JS new line character, like said here : How replace HTML <br> with newline character "\n"
Make Like This
<pre id="MyID">This is Test <br /> This is test</pre>
and javascript code
<script>
alert(document.getElementById('MyID').innerHTML);
</script>

How do I assign a HTML string over multiple lines in Javascript?

I have to assign an HTML string through the following Javascript code. However, this seems to be possible only if I put all the HTML on one line.
This works:
var assignedhtml = "<div> <p>It's the most beautiful thing I've seen in my life </p> <p> It's watermalone </p> </div>"
This does not work:
var assignedhtml = "<div>
<p>It's the most beautiful thing I've seen in my life </p>
<p> It's watermalone </p>
</div>"
The issue is that I have too many lines my html code. In the past, I have individually removed all the \n (newline) characters. Is there a simpler way to achieve the variable assignment I intend without having to individually go through the lines and delete the newline characters?
i.e., I want to keep the html code on the right as is in the second case above, but remove the newlines before assigning it to the variable.
There's no equivalent to, for instance, PHP's heredoc but you can add backslashes to escape the hard returns:
var assignedhtml = "<div>\
<p>It's the most beautiful thing I've seen in my life </p>\
<p> It's watermalone </p>\
</div>";
Here's a working example: http://jsfiddle.net/9W6BS/
One more variant - use '\' symbol at the and of line
Valid code example
var assignedhtml = "<div>\
<p>It's the most beautiful thing I've seen in my life </p>\
<p> It's watermalone </p>\
</div>"
Also want to note, that some tools ( like webStorm or PhpStorm) allow to edit such injections in normal mode ( Alt + enter - edit HTML Fragment )
You can do it like this:
var assignedhtml = '<div>' +
'<p>It\'s the most beautiful thing I've seen in my life</p>' +
'<p>It\'s watermelon</p>' +
'</div>';

Br not working inside P when using Jquery.html()

I am trying to assign to <p> element a large amount of text, which includes some <br /> tags inside, as it's html. I am using the .html() method from JQuery, but it wont show the line breaks.
My code:
var text = "Hello, this is a pretty <br/> large text with some <br/> line breaks inside"
$('.container').append("<p class='myPClass'><p>");
$('.myPClass').html(text);
it does add the text as 'myPClass' html, but it totally ignores the <br/> tags.
the result i am getting is:
<p class='myPClass'>Hello, this is a pretty large text with some line breaks inside</p>
so it would look like:
"Hello, this is a pretty large text with some line breaks inside"
what i want my result to be:
<p class='myPClass'>Hello, this is a pretty <br/> large text with some <br/> line breaks inside</p>
so it would look like:
"Hello, this is a pretty
large text with some
line breaks inside"
what is wrong with my code? or how can i get to do this?
You can also try the following:
var text = "Hello, this is a pretty" + "<br/>" + "large text with some" + "<br/>" + "line breaks inside"
$('.container').append("<p class='myPClass'><p>");
$('.myPClass').html(text);
Try this
var text = "Hello, this is a pretty <br/> large text with some <br/> line breaks inside"
$('.container').append("<p class='myPClass'></p>");
$('.myPClass').html(text);

How to escape a single quote in jQuery?

I know I can use \', but that's not the point here. Let's say I have the word "can't". It has "'" in it now. This goes in to a var in a function like so:
function active(id,clas,match,hometeam,awayteam){
So let’s say hometeam has the value of "can't". When I try to use this code:
$('#test').html(hometeam + " VS " + awayteam);
It's not working, because essentially it has:
$('#test').html(can't + " VS " + awayteam);
How do I solve this?
EDIT:
I think the problem is not in the jQuery. The line that calls this function is this line:
<input type="button" id="btn" value="1.4" class="butta" onmousedown="active('btn','buttdowna','match1','hometeam','awayteam')" />
So how do I escape this?
EDIT: I haven't found the perfect solution, so I just changed the word in my database and added the "\" for now...
This should work. If the contents have double quotes then wrap the string in single quotes and escape single quotes inside.
var hometeam = '"can\'t"';
$('#test').html(hometeam + 'VS' + awayteam)
The values returned by variables do not need to be escaped in javascript. If you are having a problem there is some other underlying issue.
EDIT: Per your question edit you will need to escape the value in the function call, if you were to use can't as one of your parameters you would need
<input type="button" id="btn" value="1.4" class="butta" onmousedown="active('btn','buttdowna','can\'t','hometeam','awayteam')" />
The problem is that you are using string operations to build HTML. Use jQuery/DOM methods instead and you won't have issues with this.
Another way would be escaping the quotes but compared to the previous suggestion that's just really ugly.
Since you are creating the HTML in PHP, do something like this:
echo '<input type="button" id="btn" value="1.4" class="butta" onmousedown=\'active("btn","buttdowna","match1",'.htmlspecialchars(json_encode($foo)).', '.htmlspecialchars(json_encode($bar)).');\' />';
You can change the HTML Part like this it will work,
<input type="button" id="btn" value="1.4" class="butta" onmousedown=active("btn","buttdowna","match1","can't","awayteam") />
In an HTML attribute without Quotation also work. Quotation is used to group. Example) title="Click Event" will work and title=Click Event will take the first value(Click) only. That is if a word doesn't contains space then no need of Quotation.

Categories