How do I assign a HTML string over multiple lines in Javascript? - 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>';

Related

New line with template literals in Angular [duplicate]

So I'm trying to do something very simple and I'm stuck. I have a String variable and within that variable I Wanna set line break so certain part of the text goes to new line.
What I have tried:
title: string = "My \n Title";
title: string = "My\ Title";
title: string = "My\
Title";
title: string = "My" + "\n" + "Title";
I have tried many variations but its just not working. Am I being stupid and missing something very obvious?
Not a duplicate as I have tried the <br/> and it has not worked.
Update:
The variable is being printed in the browser HTML like so {{title}}
Here are two demonstrably working versions...
White Space
Solution One... if you want newlines to be respected in HTML... (works with the back-tick strings, or with 'My \ntitle'...
document.getElementById('example').innerHTML = `My
title`;
h1 {
white-space: pre;
}
<h1 id="example">
</h1>
Angular Version:
<h1 style="white-space: pre;">{{title}}</h1>
HTML Break
Solution two... you want to use HTML...
document.getElementById('example').innerHTML = 'My<br />title';
<h1 id="example">
</h1>
Use ng-bind-html if you want to allow HTML during binding.
In html add style:
<div style="white-space: pre-line">{{DialogText}} </div>
Use '\n' to add newline in the typescript.
this.DialogText = "Hello" + '\n' + "World";
Same in stackblitz: https://stackblitz.com/edit/angular-rpoxr5linebreak
You can also use a readonly textarea element instead of <div or <p> to keep the format of original string.
try like this
<div ng-bind-html="myMsg"></div>
$scope.myMsg = `Below is the result: <br>Successful:1, <br>Failed:2` // Use backtick
You have done the right thing.
But if you are showing this in a browser, the \n means didley.
You have to do:
title: string = "My<br>Title"
Now if you are using a fancy front end tool like React, you will have to deal with unsafe HTML in strings...

How to get line break within string interpolation in Angularjs

So I'm trying to do something very simple and I'm stuck. I have a String variable and within that variable I Wanna set line break so certain part of the text goes to new line.
What I have tried:
title: string = "My \n Title";
title: string = "My\ Title";
title: string = "My\
Title";
title: string = "My" + "\n" + "Title";
I have tried many variations but its just not working. Am I being stupid and missing something very obvious?
Not a duplicate as I have tried the <br/> and it has not worked.
Update:
The variable is being printed in the browser HTML like so {{title}}
Here are two demonstrably working versions...
White Space
Solution One... if you want newlines to be respected in HTML... (works with the back-tick strings, or with 'My \ntitle'...
document.getElementById('example').innerHTML = `My
title`;
h1 {
white-space: pre;
}
<h1 id="example">
</h1>
Angular Version:
<h1 style="white-space: pre;">{{title}}</h1>
HTML Break
Solution two... you want to use HTML...
document.getElementById('example').innerHTML = 'My<br />title';
<h1 id="example">
</h1>
Use ng-bind-html if you want to allow HTML during binding.
In html add style:
<div style="white-space: pre-line">{{DialogText}} </div>
Use '\n' to add newline in the typescript.
this.DialogText = "Hello" + '\n' + "World";
Same in stackblitz: https://stackblitz.com/edit/angular-rpoxr5linebreak
You can also use a readonly textarea element instead of <div or <p> to keep the format of original string.
try like this
<div ng-bind-html="myMsg"></div>
$scope.myMsg = `Below is the result: <br>Successful:1, <br>Failed:2` // Use backtick
You have done the right thing.
But if you are showing this in a browser, the \n means didley.
You have to do:
title: string = "My<br>Title"
Now if you are using a fancy front end tool like React, you will have to deal with unsafe HTML in strings...

Creating functions containing HTML

I'm trying to create a Coffescript function that contains common HTML for a frequently re-used object in my page. I'm passing a variable to the function with the text I want changed each time. Every time I try to compile my Coffeescript, I get this error:
[stdin]:6:5: error: unexpected identifier
<p>"text1"</p>
^^^^^
Here's my code
text1 = "Some text"
ballon1 = (text1) ->
"Open Modal
<blockquote class=\"balloon\" id=\"balloon1\">
<p>"text1"</p>
X
</blockquote>"
I was hoping the output would be:
Open Modal
<blockquote class="balloon" id="balloon1\">
<p>Some text</p>
X
</blockquote>
Any thoughts? I was trying to find the language for the job; maybe I should be using PHP instead? Also, I'm using Javascript because I thought the code needed to be run client-side, since I want to pass different text to the function depending on what links are clicked and when.
Since this is CoffeeScript, you can use string interpolation:
ballon1 = (text1) ->
"Open Modal
<blockquote class=\"balloon\" id=\"balloon1\">
<p>#{text1}</p>
X
</blockquote>"
You could also switch to single quotes in your HTML to avoid all the backslashes:
ballon1 = (text1) ->
"<a href='#balloon1'>Open Modal</a>
<blockquote class='balloon' id='balloon1'>
<p>#{text1}</p>
<a href='#close' title='Close' class='close'>X</a>
</blockquote>"
Or, if you're like me a think single quotes look funny in HTML, you could use a block string for your HTML snippet:
ballon1 = (text1) ->
"""
Open Modal
<blockquote class="balloon" id="balloon1">
<p>#{text1}</p>
X
</blockquote>
"""
A block string even lets you nicely indent the HTML for readability. This is the version I'd probably go with.
If you want string concatenation, you want the + operator:
ballon1 = (text1) ->
"Open Modal
<blockquote class=\"balloon\" id=\"balloon1\">
<p>" + text1 + "</p>
X
</blockquote>"
Change is on the fourth line.
That said, you might consider looking into templating libraries if this is something that comes up a lot. That way (with many of them) you can author your templates in an HTML editor, embedding them in your page, and not have to fuss about with quote character escaping.

Interpreting HTML Tags in Javascript String Literal

I make an AJAX call that gives me a string within a JSON object containing text formatted like this:
Your girl was in Berkeley with a communist reader. <br> Mine was entombed within boombox and walkman. <br> I was a hoarder, but girl, that was back then. <br> The gloves are off, the wisdom teeth are out. <br> What you on about? <br> I can feel it in my bones. <br> I can feel it in my bones. <br> I'm stronger now, I'm ready for the house. <br> Such a modest mouse. <br> I can't do this alone.
I use this string to populate a div on my webpage, such that it appears like this:
<div class="lyrics-container>{{ the text in the JSON string }} </div>
However, when populating the div with that text, I get the exact string, meaning that the <br>s show up as text. I want them to actually perform their function and break the line. Is there a way to coerce the browser into interpreting HTML within a string?
I'm using Angular to grab the data and populate the div if that makes any difference.
It is not straight forward. You need to use ngBindHtml.
Controller
$scope.content = "<b>this is bold content</b>";
HTML
<div ng-bind-html="content"></div>
You'll need the following module:
http://code.angularjs.org/1.0.3/angular-sanitize.js
Be sure to declare ngSanitize as a module dependancy, like this:
var app = angular.module('angularjs-starter', ["ngSanitize"]);
You can use ng-bind-html-unsafe.
<span ng-bind-html-unsafe="content"></span>
Demo

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);

Categories