javascript display multi-line text - javascript

I try to display a multi-lined text but it always apears as one line.
For example:
var text ="line 1. \n line 2. \n line 3."
It it supposed to be displayed like :
line 1.
line 2.
line 3.
but instead I end up with
line 1. line 2. line 3.
in a rendered html page.
I tryed jquery text and html methods but not working.
Even through angularjs, it is always the same.
$('#element').text(text);
$('#element').html(text);
or
<div>{{ text }}</div>
Isn't there a way to get what I'm expecting?

Try Something like
<div class="angular-with-newlines">
{{ text }}
</div>
css
/* in the css file or in a style block */
.angular-with-newlines {
white-space: pre-wrap;
}
This will use newlines and whitespace as given, but also break content at the content boundaries. More information about the white-space property can be found here:
https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
If you want to break on newlines, but also collapse multiple spaces or white space preceeding the text (very similar to the original browser behaviour), you can use:
white-space: pre-line;

May be, this is what you want...
<textarea id="text"></textarea>
<p id="text2"></p>
<button onclick="multi_line_textarea()">on textarea</button>
<button onclick="multi_line_para()">on paragraph</button>
<script>
function multi_line_textarea(){
var text = "line 1. \nline 2. \nline 3.";
var el = document.getElementById('text');
el.innerHTML = text;
}
function multi_line_para(){
var text2 = "line 1. <br/>line 2. <br/>line 3.";
var el2 = document.getElementById('text2');
el2.innerHTML = text2;
}
</script>
Here's a jsFiddle:https://jsfiddle.net/p984fd1m/2/
Hope that helps..

Try like this.
<p style="white-space: pre-line;">{{ text }}</p>

Related

How to display paragraphs coming from a single element in Angular with the required characters working

I have a object in view.component.ts file coming form backend. It is supposed to be description for a product. It has more than 500 lines of text. for eg:
{"description" : "Hello my Name is Param Bedi.\r\nHow are you\r\n\r...continue till 500 lines and more"}
I need to display this to Angular view. But its just coming straight as it is ie containing all the "\r\n" etc. Its not inserting a new line instead of \n.
This is what I am doing in view.component.html
<div>
<p>{{ data["description"] }}</p>
</div>
What should I do so that I can display the data with newline and other special characters working?
You can use HTMLElement.innerText:
<div>
<p [innerText]="data.description"></p>
</div>
Or, if you need special character output, using Element.innerHTML (with replacing new lines with <br>):
<div>
<p [innerHTML]="data.description.replace(/(\r\n|\r|\n)/g, '<br>')"></p>
</div>
Solution 1: You can use white-space: pre-line in css. You can check here CSS White Space.
Solution 2: You can use Textarea with readonly.
<textarea name="description" readonly [(ngModel)]="data.descrption" style="resize: none;" ></textarea>

.text() concatenates strings without spaces when removing html tags

I have a rich text editor on my site and I am trying to create a reliable word counter for it.
Because it's a rich text editor it (potentially) contains html.
This html might be, for example:
<div class="textEditor">
<h1><strong>this is a sample heading</strong></h1>
<p><br></p>
<p>and this is a sample paragraph</p>
</div>
To get a reliable word count I am trying to first convert the html to text using:
var value = $('.textEditor').text()
The problem I am facing is the string that is returned seems to concatenate where it removes the html tags and what I am left with is:
this is a sample headingand this is a sample paragraph
as you can see, the words 'heading' 'and' are joined to become 'headingand' which would give me a word count of 10 instead of 11.
any thoughts on how to properly achieve this would be much appreciated :)
You can use innerText:
var value = document.querySelector('.textEditor').innerText
or
var value = $('.textEditor')[0].innerText
console.log(document.body.innerText)
<div class="textEditor">
<h1><strong>this is a sample heading</strong></h1>
<p><br></p>
<p>and this is a sample paragraph</p>
</div>
I had a bit of playing around with it and came up with the following:
let value = $('.textEditor').text();
function read(){
alert(value.trim().split(/\s+/).length);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="textEditor">
<h1><strong>this is a sample heading</strong></h1>
<p><br></p>
<p>and this is a sample paragraph</p>
</div>
<button onclick="read()">Read</button>
https://codepen.io/anon/pen/YOazqG?editors=1010
Just trim it and split and you should be fine.

Set text in <textarea>, including newlines

I want to set the text in a <textarea> from a js-function; I'm simply setting the innerText-attribute to a new value. The text is multiline and should be displayed as such. However, newlines are dropped by the browser and the entire text is displayed as one line:
document.getElementById("my_textarea1").innerText = "foo\nbar"; // displayed as "foobar"
document.getElementById("my_textarea2").innerText = "foo\
bar"; // displayed as "foobar"
document.getElementById("my_textarea3").innerText = `foo\
bar`; // again, "foobar"
<textarea id="my_textarea1"></textarea>
<textarea id="my_textarea2"></textarea>
<textarea id="my_textarea3"></textarea>
Is there a way to preserve newlines when setting the text in a <textarea>?
Try it. I use property "value" or "innerHTML" or "textContent":
var area = document.getElementById("my_textarea");
area.value = "foo\nbar";
var area_2 = document.getElementById("my_textarea_2");
area_2.innerHTML = "foo\nbar";
var area_3 = document.getElementById("my_textarea_3");
area_3.textContent = "foo\nbar";
<textarea id="my_textarea"></textarea>
<textarea id="my_textarea_2"></textarea>
<textarea id="my_textarea_3"></textarea>
You can set the value of the textarea, this works with \n, and
`foo\
bar`;
document.querySelector("#my_textarea").value = "foo\nbar"
<textarea id="my_textarea"></textarea>
If that doesn't work for you, use the innerHTML property, the same way:
document.querySelector("#my_textarea").innerHTML = "foo\nbar"
<textarea id="my_textarea"></textarea>
Use area.innerHTML instead, innerText property strips off the new line character
var area = document.getElementById("my_textarea");
area.innerHTML = "foo\nbar";
<textarea id="my_textarea">
</textarea>
You can use \r or \n for this.
Additionally HTML also supports \t to apply tab between two words.
document.querySelector("#my_textarea1").value = "foo\rbar"
document.querySelector("#my_textarea2").value = "foo\nbar"
document.querySelector("#my_textarea3").value = "foo\tbar"
<!DOCTYPE html>
<html>
<body>
<p>New line using "\r" :</p>
<textarea id="my_textarea1"></textarea>
<br>
<p>New line using "\n" :</p>
<textarea id="my_textarea2"></textarea>
<br>
<p>Tab between tow words using "\t" :</p>
<textarea id="my_textarea3"></textarea>
</body>
</html>
According to the HTML Spec:
element . innerText [ = value ]
Returns the element's text content "as rendered".
Can be set, to replace the element's children with the given value, but with line breaks converted to br elements.
Meaning, what you have should have worked. As noted by other answers you could use textContent, value, innerHTML all of which are more likely to work.
If you are set on using textContent, you have a few options/peculiarities, which I'll list out below:
Use an ES6 transpiler such as Babel.js
You can test by enabling ES6 in Stack Overflow's snippet editor.
Refer to (3) options in the snippet below
Note: these seem to work in OSX Safari but not Google Chrome
// Call toString() method
document.getElementById('my_textarea').innerText = "foo\nbar".toString();
// Include the line return character
document.getElementById('my_textarea2').innerText = "foo\r\nbar";
// Apparently, any whitespace or escape character will work
document.getElementById('my_textarea3').innerText = "foo \nbar";
<textarea id="my_textarea"></textarea>
<textarea id="my_textarea2"></textarea>
<textarea id="my_textarea3"></textarea>

newline character does not work when parsing as JSON string object

I was having some trouble phrasing that title, but my problem is that the \n characters in strings in my JSON dictionary get nullified when I parse to html.
var exp = {
"globalRunInfo" : {
"file" : "file/path/goes/here",
"info" : "random junk here",
"copyright" : "this is where I am getting my problem \n the newline doesn't work \n so all this gets formatted as one line"
}
}
ko.applyBindings(exp);
<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="with: globalRunInfo">
<p data-bind="text: file"></p>
<p>SOMETHING</p>
<p data-bind="text: info"></p>
<span data-bind="text: copyright"></span>
</div>
</html>
Does anyone know how to fix this? I'm trying to avoid writing a function that checks for newline characters and replaces them with breaks or something. It's a lot of work for something that I'm going to use once.
Try setting the CSS property white-space: pre-wrap on the span element. This will result in the braking of the new line character.
<span style="white-space: pre-wrap" data-bind="text: copyright"></span>
You can assign a class to the area and use white-space: pre-wrap
Taken from the white-space documentation:
pre-wrap
Sequences of whitespace are preserved. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.
In addition you can also remove the extra space after \n so you don't get the space added to the front of the new line.
var exp = {
"globalRunInfo" : {
"file" : "file/path/goes/here",
"info" : "random junk here",
"copyright" : "this is where I am getting my problem \nthe newline doesn't work \nso all this gets formatted as one line"
}
}
ko.applyBindings(exp);
.example{
white-space: pre-wrap;
}
<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="with: globalRunInfo">
<p data-bind="text: file"></p>
<p>SOMETHING</p>
<p data-bind="text: info"></p>
<span class="example" data-bind="text: copyright"></span>
</div>
</html>
wrap the whole json text with pre tag. it worked with me

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