I have this simple JavaScript:
function property() {
var ua = document.getElementById('greenBack').innerHTML;
var finals;
finals = ua;
if (ua.indexOf('p')) {
finals += '<br>\n Unknown Error';
}
return finals;
}
The problem is that I would like a newline to be shown when the function output is displayed in console.log() without the <br> tag (because <br> displays on the console) , but also be able to write the text "Unknown Error" to a newline in html without using <br>.
Is there any solution to display a newline in HTML and the console without \nor <br> ?
Just use \n for the console output. Then, when showing the text on a HTML page, you can either:
replace \n with <br>
or wrap a <pre> tag around it which will respect white-space and newlines
or use CSS-style white-space: pre-wrap; on any other HTML element
See this jsFiddle
$('#test').text('This\n is\n a\ntest');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="test"></pre>
You can print your information in a textarea. It will use the \n for the new line as the console
pre tag what you write it display all as it is including space, \n used for new line, br tag also to move to new line, some more option comes in handy when you use js literal represented as and found on key board between esc and tap button with sign ** `** variable can be put in side ${variable inside here}.
Related
I think it is a bit simple question but I couldn't find my answer neither on Stackoverflow nor Google. Here is my question. I want to output strings with escape characters. I have used the method document.getElementIdBy().
Here is my example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<p id="example1"></p><br>
<p id="example2"></p><br>
<p id="example3"></p><br>
<p id="example4"></p><br>
<script>
var x = "\"ABC\""
var y = "\'ABC\'"
var z = "ABC\nDEF"
var t = "ABC\bDEF"
document.getElementById("example1").innerHTML=x;
document.getElementById("example2").innerHTML=y;
document.getElementById("example3").innerHTML=z;
document.getElementById("example4").innerHTML=t;
</script>
</body>
</html>
The first two works fine. The third one doesn't create a new line and the fourth one doesn't crate a backspace. I assume that the variable z is like this
ABC
DEF
If I write this into a p element, it must show up like this: ABC DEF. Therefore I can understand why it doesn't appear as I expected (If I style the p element with white-space:pre it works as I expected)
However I wonder why \b escape character doesn't work as expected. Actually I was expecting the output to be: ABDEF (without C). There may be some logic similar to the upper one but I cannot find. Can someone explain why it doesn't work?
I think these chars are just stripped from HTML, you could achieve what you want by replacing \n with <br/>
e.g.
document.getElementById("example3").innerHTML=z.replace("\n","<br/>");
The third one doesn't create a new line
New lines in text are ignored in HTML tags. They are rendered as a space. Use <pre> tags to keep formatting:
<pre id="example3"></pre>
Or add <p> tags instead of new lines:
var z = "<p>ABC</p><p>DEF</p>"
Or <br>
var z = "ABC<br>DEF"
the fourth one doesn't crate a backspace
Do not pretty sure that HTML/JS supports \b.
new line (\n) doesn't generate new line in html.
so if you write:
<p>first line
second line</p>
you will get:first line second line.
so to write \n to html you must convert it to <br>.
document.getElementById("example3").innerHTML=z.replace(/\n/g,'<br>');
this regular expression replaces all \n with <br>.
and \b is just character with code 8. its special behavior occurs only when you send it to an input or text box.
When I paste text into my iFrame in IE11 it ignores the /n and instead turns it into whitespace. As I would like to maintain format of pasted text, I wish to keep new lines.
Since IE automatically handles new lines as new paragraphs, I would prefer to keep it that way when pasting text. Here is my code
//Html is the text obtained from the clipboard. New lines are stored as /n
html = html.replace(/\n\n/g, '</p><p><br>');
html = html.replace(/\n/g, '</p><p>');
html = '<p>'+html+'</p>'
This works fine for the most part, although the browser for some reasons adds an extra p tag at the start of the pasted text (but no closing tag)
This has resulted in quite a few annoying bugs. Is there any better way to go about this?
You can do split/join methods, look at this example. For following html:
<textarea class="pasted_text">Line 1
Line 2
Line 3
Line 5
</textarea>
<h4>Result (paragraphs have blue border):</h4>
<div class="result_text"></div>
We split the string using \n, clean and than join with paragraph tags:
var pastedText = $('.pasted_text').val();
/* Split text on new lines */
var split = pastedText.split('\n');
/* Remove empty paragraphs */
var clean = split.filter(function(n){ return n });
/* Join back with paragraph tags */
var joined = clean.join('</p><p>');
/* Enclose with paragraph */
var result = '<p>'+joined+'</p>';
/* Print output */
$('.result_text').html( result );
I think replacing p by div should fix it. The p tag is tricky.
JavaScript converts my < into >. I want to alert it but my message is with encoded marks like ##&*()}{>?>? - how to display it normally but prevent from executing as HTML code?
<span id="ID" onClick="alertIt(this.id);">
<p>Some string with special chars: ~!##&*()}{>?>?>|{">##$#^#$</p>
<p>Why when clicked it gives something like this:</p>
<p>'<br>
Some string with special chars: ~!##&*()}{>?>?>|... and so on
<br>'</p>
</span>
<script type="text/javascript">
function alertIt(ID)
{
var ID = ID;
var content = document.getElementById(ID).innerHTML;
alert(content);
}
</script>
Use innerText instead of innerHTML. http://jsfiddle.net/WVf95/
Your problem is that you use the wrong approach to get the text to display with alert().
Some characters are illegal in HTML text (they are used for HTML tags and entities). innerHTML will make sure that text is properly escaped (i.e. you can see tags and escaped text).
If you want to see tag and text in alert(), there is no solution.
If you want only the text, then you will have to extract it yourself. There is no built-in support for that. It's also not really trivial to implement. I suggest to include jQuery in your page; then you can get the text with:
function alertIt(ID) {
alert($(ID).text());
}
Using textContent instaed of innerHTML or innerText is a solution.
When adding in text with small whitespace appended to it for alignment purposes the whitespace is trimmed off (the whitespace is added in c# so by the time it gets to front end Javascript it cannot be edited - it would be nice to just use some CSS to do this but it is not an option).
Here is what I tried so far:
var zlp = document.getElementById("testDiv")
zlp.innerHTML = "hello hello"
var zzz = document.createTextNode("hello hello")
zlp.appendChild(zzz)
<div id="testDiv"></div>
Both of which produce hello hello.
White space characters are usually collapsed in HTML (by default).
You can replace it with the entity:
var text = text.replace(/\s/g, ' ');
\s will match any white space character, such as space, tab and new line. If you only want to replace space, use / /g instead.
Other options which avoid string manipulation:
Put the text in a pre element.
Set the CSS 2 white-space property to pre as #Esailija pointed out. You can always add CSS properties dynamically to elements, they don't have to be specified in a style sheet.
use
zlp.innerHTML = "hello hello";
Like everyone else just said.
use a html tag 'pre'
Example:
<pre>
A line
A line with indent
</pre>
result:
A line
A line with indent
White space is collapsed in HTML. It's not a JS issue, the same would happen if you typed that manually in the HTML document. You need to replace the spaces with
zlp.innerHTML = "hello hello".replace( / /g, " " );
my coding:
...
<textarea name="TextArea1" id="TextArea" style="height ; width" ></textarea>
...
<script type="text/javascript">
var txt_element = document.getElementById("TextArea");
document.write (txt_element.childNodes[0].nodeValue);
</script>
...
but it doesn't recognize "enter/return" key hited instead it shows " "
Many thanks
To expand on Chris's answer, the problem is that the browser is rendering the text you write in the same way as it renders any other piece of html, which means white space (including carriage returns) is treated as a word separator, not a line or paragraph separator. And multiple consecutive white space characters are condensed down to a single space. This is explained further in the html spec.
This is different to how it treats text within a textarea element.
So as Chris suggested, you need to replace carriage returns in your string with html <br> elements:
var enteredText = document.getElementById("TextArea").value;
var updatedText = enteredText.replace(/\n/g, '<br />');
document.write(updatedText);
Note: you should be able to get the textarea's value directly with .value rather than saying .childNodes[0].nodeValue.
Note 2: I second what Chris said about document.write() - it is usually not the best option.
Note 3: If you're catering for non-Windows system you may also need to replace \r.
Text areas use \n to designate a new line, something along these lines should work:
string = document.getElementById("TextArea")childNodes[0].nodeValue;
string = string.replace(/\n/g, '<br />');
document.write('string');
Not sure if you're just goofing around, but I feel compelled to mention that generally speaking you should never use document.write().