How to put linebreaks on dynamically generated javascript code - javascript

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>

Related

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

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.

Escaping HTML in JavaScript

When I'm building HTML in JavaScript I'm constantly escaping double quotes. E.g.
$(wrapper).append("<input type=\"text\" name=\"thingummy[" + id + "]\" data-id=\"" + data_id + "\" id=\"" + id + "_" + data_id + "\" /> <br>");
and, when there are many quotation marks, I'm constantly making mistakes over which quotes I've escaped. And I end up spending more time than I'd like fixing them.
Is there a better (quicker / safer / more legible) way of building HTML than the approach I'm using?
UPDATE
One rather important point I forgot to mention! I'm outputting this JavaScript using PHP. So, I have code like this:
echo '$(wrapper).append("<input type=\"text\" name=\"thingummy[" + id + "]\" data-id=\"" + data_id + "\" id=\"" + id + "_" + data_id + "\" /> <br>");';
which makes using single quotation marks a problem ('cos they end up breaking the PHP! Which is another problem I keep experiencing when I forget I'm in the middle of some PHP and use a single quotation mark as mentioned in a comment below).
You could perhaps use templating strings in JavaScript. Makes it simple to insert variables into a string too with ${var} syntax.
echo '$(wrapper).append(`<input type="text" name="thingummy[${id}]" data-id="${data_id}" id="${id}_${data_id}" /> <br>`);';
You could use heredoc syntax like this:
<?php
echo <<<JAVASCRIPT
<script type="text/javascript">
alert("some javascript code where you don't have to escape double quotes");
</script>
JAVASCRIPT;
This would simplify you work.
Or you can close your php tag and open it again, like this:
<?php
$somePhpCode = 1;
?>
<script type="text/javascript">
alert("some javascript code where you don't have to escape double quotes");
</script>
<?php
$somePhpCode = 2;
?>

\n not working in Javascript [duplicate]

This question already has answers here:
Line break in the mailto onclick
(2 answers)
What is the JavaScript string newline character?
(15 answers)
Closed 8 years ago.
For some reason \n isn't working for me in javascript. Is there anyway to fix it or use html? In my case, I think that using <br> will not work in my href. What are your suggestions.
Working JSFiddle here.
HTML:
<a id = 'emailoff' href = "" target = "_blank">
<div id= "btn1">
<h2 id = "enter">Send Email</h2>
</div>
</a>
Javascript:
$('#btn1').click(function() {
$("#emailoff").attr("href", "mailto:" +
"?subject=Your ThinOptics glasses" +
"&body=To get your new ThinOptics glasses simply click this link and pick the case and color you like best. You'll get free shipping on your order. \n"+
" WWw.Thinoptics.Com/teddy#shalon.com \n" +
"\n Enjoy")
});
You have to URL encode your new lines. The encoded new line should be %0A http://jsfiddle.net/mendesjuan/LSUAh/
<a id = 'emailoff' href = "mailto:me#you.com?subject=hello&body=a%0Ab" target = "_blank">
<div id= "btn1">
<h2 id = "enter">Send Email</h2>
</div>
</a>
If you're doing it in JS, use the following
$('#btn1').click(function() {
$("#emailoff").attr("href", "mailto:" +
"?subject=Your ThinOptics glasses" +
"&body=To get your new ThinOptics glasses simply click this link and pick the case and color you like best. You'll get free shipping on your order. %0A"+
" WWw.Thinoptics.Com/teddy#shalon.com %0A" +
" %0A Enjoy")
});
Note that you don't have to hardcode the URL encoded version, you can use
encodeURIComponent("\n") // %0A
P.S. Wouldn't it be better not to rely on the user's mail client being configured? Use your own server to send the email instead to make sure all users can send a message.
Try
<br>
instead of
\n
\n is rendered as 1 space in html and so is \t or \s

Removing HTML from a jQuery .append()

I have a Parse.com backend and am rendering its data, ultimately, with a jQuery append, like this:
$(".albums").append(
"<div class='col-xs-6 col-6 col-sm-3 col-lg-3'><div class='flip animated fadeInDown' style='-webkit-animation-delay:" + i * 0.1 + "s'><div class='card'><div class='album front' style='background-image:url(" + bigImg + ")'><img class='artwork' src='" + artwork + "' alt='" + collectionName + "' /></div><div class='album back' style='background-image:url(" + back + ")'><img class='artwork' src='" + back + "' alt='" + collectionName + "' /></div></div></div></div>");
It's a for loop hence the need for the various HTML elements and their classes. I know it's an appalling, shameful way to do it (and I believe it's causing a memory leak).
My questions are: How can I remove as much of the HTML from this append statement as possible? Should I be using a templating language?
If you think you might want to use a templating language you can start by building your own, super simple, template.
Simply replace
"some string stuff " + someValue + " some more stuff"
// instead
var myTemplate = "some string stuff {someValue} some more stuff";
// now render
myTemplate.replace('{someValue}', someValue);
It's easy to go further, and wrap this in a function to "render" that takes an object as an argument and iterates over keys. Done carefully this will provide you a subset of the functionality provided by "off-the-shelf" templating libraries so you can always cut-over later.
This will allow you to predefine your "template" and render using the data input provided. The next question is where do you want to define your template. Generally you would relocate it to a separate free-standing file that the designers would have access to, perhaps in a "templates" directory. But then you have to load it.
If you have lots of templates, some libraries would allow you to pack them together in one file, load the file, then ask the library for a specific template by name. Your designers would then control this file and the CSS that goes with it. If you have a lot of this, then the architectural overhead starts to make sense.
Whether you want to go down that road really depends on your specific circumstances and the structure of your project team.
I like Handlebar for this sort of thing.
This would be the template
<script id="albumsTemplate" type="text/x-handlebars-template">
<div class='col-xs-6 col-6 col-sm-3 col-lg-3'>
<div class='flip animated fadeInDown' style='-webkit-animation-delay:{{delay}}s'>
<div class='card'>
<div class='album front' style='background-image:url({{bigImg}})'>
<img class='artwork' src='" + artwork + "' alt='{{collectionName}}' />
</div>
<div class='album back' style='background-image:url({{back}})'>
<img class='artwork' src='" + back + "' alt='{{collectionName}}' />
</div>
</div>
</div>
</div>
</script>
And then you would use it like this:
var source = $("#albumsTemplate").html();
var template = Handlebars.compile(source);
var html = template({delay:i*0.1,
bigImg:bigImg,
collectionName:collectionName,
back:back});
$(".albums").append(html)
Adding html() to the call should do it. That'll return the html inside of .albums. To get everything including .albums you do $('.albums').append(...).parent().html().

Replace all html attribute definitions that use single quotes with double quotes

I have an html string and I want to replace any instance of an html attribute being set with single quotes with double quotes.
So for example, I want to replace
<script src='foo.js'></script>
with
<script src="foo.js"></script>
However, I want to do this without affecting any single quotes that might be in javascript statements or in text within the html.
Eg
<script> var foo = '67'; </script>
should be unaffected and
<div id='foo'> 'hi' </div>
should become
<div id="foo"> 'hi' </div>
Is there any easy way to do this?
For a given element selecting it with jquery and then reading its outerHTML does this but I want to do it to an entire page of html all at once.
Thanks!
Try this:
var str = "<br style = 'width:100px'/> test link";
var regex = /<\w+\s*(\w+\s*=\s*(['][^']*['])|(["][^"]*["]))*\s*[\/]?>/g;
var rstr = str.replace(regex, function($0,$1,$2){
return $0.replace($2, $2.replace(/'/g, '"'));
});
console.log('replaced string = ' + rstr);
You can refector it to strictly match your case.
Answering my own question as I think the easiest solution to this is what is shown in this fiddle and does not require jquery or regexps:
http://jsfiddle.net/QdUR5/1/
<html id="foo"></html>​
var htmlString =
'<head>' +
'<script type="text/javascript" src=\'main.js\'></scr' + 'ipt>' +
'</head>' +
'<body onload=\'onLoad()\'>' +
'</body>' ;
document.getElementById('foo').innerHTML = htmlString;
console.log(document.getElementById('foo').outerHTML);
​
Basically you just need to set the inner html of an html element to the html string without the html tags and then output the html elements outer html.
I think that is a bit simpler than using a regexp although that is an awesome regexp Mike :)

Categories