How do I display new line in .text() in jQuery? - javascript

I have the following code:
var stringDisplay = "Hello\nWorld";
$("#meaning").text(stringDisplay);
It is displaying \n instead of a newline.
The output is showing up as Hello\nWorld.
I used <br> tag also in place of \n, but it's still not working.

You will have to use both .html() and replace the newline:
var escaped = $('<div>').text(stringDisplay).text();
$('#meaning').html(escaped.replace(/\n/g, '<br />'));
An alternative would be to style the element:
white-space: pre-wrap;

How about this
$('meaning').html('line1<br>line2');

Related

How to prevent non-breaking spaces from being created in a contenteditable element?

I have a contenteditable div, which creates many non-breaking spaces when words are deleted or added. This is the format of my code:
<div id="div" contenteditable="true">
<span>Hello</span>
<span></span>
</div>
I've tried replacing non-breaking spaces on input:
document.getElementById("div").oninput = function() {
document.getElementById("div").innerHTML.replace(" ","");
}
But this doesn't work. Any ideas?
You need to assign the innerHTML to the changed text like so:
document.getElementById("div").oninput = function() {
document.getElementById("div").innerHTML = document.getElementById("div").innerHTML.replace(" ","");
}
Because as shown in this MDN page:
The original string is left unchanged
So you need to assign the result of replace to something.
Another solution without any JavaScript at all: just add white-space: pre-wrap; or white-space: break-spaces; to the styles of your content editable element... and voilà, no more :)
you have used getElementById(), while you are not using any id in your HTML code, beside the above answer mentioned the innerHTML problem

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.

Why does the innerHTML property automatically trims the string?

here is my code:
function myFunction() {
var str = " Hello World ";
document.getElementById("demo").innerHTML=str;
alert(str);
}
<p id="demo"></p>
<button onclick="myFunction()">Try it</button>
While the Alert window outputs the string as it is i.e with spaces, the p element receives the string in trimmed form i.e with no spaces?
In HTML, regular whitespace chararacters between tags are not interpreted as whitespaces to render by the browser.
Declaring one or multiple of them will give the same result: they are collapsed and are rendered as a single space.
To render multiple whitespaces, you have two ways :
in plain HTML use the entity ( , or non-breaking space)
in CSS, use the white-space property: white-space: pre-wrap;
pre-wrap
Sequences of whitespace are preserved. Lines are broken at newline
characters, at <br>, and as necessary to fill line boxes.
Source: MDN’s article on white-space
It is not the innerHTML. Real culprit is Browser. You cannot see the spaces in the browser directly with string literals as all browsers will always truncate spaces in HTML. You have use &nbsp to see them.
While browser processing your html, it follows some rules.
Here is the 16.6.1 The 'white-space' processing model
If 'white-space' is set to 'normal', 'nowrap', or 'pre-line',
every tab (U+0009) is converted to a space (U+0020)
any space (U+0020) following another space (U+0020) — even a space before the inline, if that space also has 'white-space' set to 'normal', 'nowrap' or 'pre-line' — is removed.
If you would like to see those whitespaces, you could use CSS's white-space property and set it to pre (which breaks only on given line-breaks) or pre-wrap (which breaks whenever necessary).
However are you sure, that you really want to do positioning of text in HTML? Is there any reason that you leave the spaces and instead use padding on your element to shift its content?
It depends on the browser.
If you wanna be sure to have the space, do this:
function myFunction() {
var str = " Hello World ";
document.getElementById("demo").innerHTML="&nbsp" + str + "&nbsp";
alert(str);
}
myFunction();

get all words without html tags with javascript regex

i try to use an regex expression to get all words without html tags
the goal of this is to tag all words with span tags to be capable to get the word when my mouse is over, but keep html initial tags
for example this code
<p>hello i'm <b>jesus</b></p>
should become
<p><span>hello</span> <span>i'm</span><b><span>jesus<span></b></p>
So, first step for me, is to get all words, without html tags, and then replace it with span
This is my regex in javascript
([^\r\n\t\f>< /]+(?!>))
But i have some problems with some tags like
Live example here
Finally , when my regex will be ok, i will be ok to replace all words by
$(this).html($(this).html().replace(reg, "$1"));
thx for your help
Maybe there is an other way to do this ...
Use .split() to split the textContent of the element. Array#forEach to iterate array after .split and appendChild to append Element.
var ELEMENT = document.getElementsByTagName('p')[0];
var text = ELEMENT.textContent;
ELEMENT.innerHTML = '';
text.split(' ').forEach(function(elem) {
var span = document.createElement('span');
span.innerHTML = elem;
ELEMENT.appendChild(span);
});
span {
margin-left: 10px;
}
<p>hello i'm <b>jesus</b>
</p>
Fiddle Demo

jQuery javascript regex Replace <br> with \n

How do i write a regex to replace <br /> or <br> with \n. I'm trying to move text from div to textarea, but don't want <br>'s to show in the textarea, so i want to replace then with \n.
var str = document.getElementById('mydiv').innerHTML;
document.getElementById('mytextarea').innerHTML = str.replace(/<br\s*[\/]?>/gi, "\n");
or using jQuery:
var str = $("#mydiv").html();
var regex = /<br\s*[\/]?>/gi;
$("#mydiv").html(str.replace(regex, "\n"));
example
edit: added i flag
edit2: you can use /<br[^>]*>/gi which will match anything between the br and slash if you have for example <br class="clear" />
myString.replace(/<br ?\/?>/g, "\n")
True jQuery way if you want to change directly the DOM without messing with inner HTML:
$('#text').find('br').prepend(document.createTextNode('\n')).remove();
Prepend inserts inside the element, before() is the method we need here:
$('#text').find('br').before(document.createTextNode('\n')).remove();
Code will find any <br> elements, insert raw text with new line character and then remove the <br> elements.
This should be faster if you work with long texts since there are no string operations here.
To display the new lines:
$('#text').css('white-space', 'pre-line');
a cheap and nasty would be:
jQuery("#myDiv").html().replace("<br>", "\n").replace("<br />", "\n")
EDIT
jQuery("#myTextArea").val(
jQuery("#myDiv").html()
.replace(/\<br\>/g, "\n")
.replace(/\<br \/\>/g, "\n")
);
Also created a jsfiddle if needed: http://jsfiddle.net/2D3xx/
Not really anything to do with jQuery, but if you want to trim a pattern from a string, then use a regular expression:
<textarea id="ta0"></textarea>
<button onclick="
var ta = document.getElementById('ta0');
var text = 'some<br>text<br />to<br/>replace';
var re = /<br *\/?>/gi;
ta.value = text.replace(re, '\n');
">Add stuff to text area</button>

Categories