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.
Related
I would like to dynamically print a string (which is NOT constant) in a certain area (eg, div result). Then I use the following code:
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
var elt = document.createElement("span");
elt.innerHTML = "=A2<C2";
document.querySelector("#result").appendChild(elt);
</script>
</body>
</html>
The problem is that if the string I want to print contains <, it interprets that and does not print < faithfully. For example, the above code prints =A2.
I see some threads proposing to replace < by < + space. But I don't like the space inserted. Additionally, I don't know if there are other special characters that will be interpreted.
So does anyone know any general solution to print a string faithfully?
PS: JSBin
You can substitute .textContent for .innerHTML
elt.textContent = "=A2<C2";
Definitely don't insert text with innerHTML; only insert HTML that way. Inserting text is a bit more verbose, but not too difficult:
elt.appendChild(document.createTextNode("=A2<C2"));
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}.
Let's say I have a large wall of text that I've pasted onto my page inside a div with id "story". Each paragraph is actually on a single line in the html file, and each paragraph is separated by a single line. I want to make the wall of text more readable using bootstrap. I've set the css in a blog like format, is there any way to dynamically add </p><p> at every paragraph separation?
var paragraphs = "your text".split(/\n\s*\n/);//since paragraphs are separated by
for(var i = 0; i < paragraphs.length; i++){ //a line, we need two \n here.
var p = document.createElement("p");
p.innerHTML = paragraphs[i].trim();
document.querySelector("#story").appendChild(p);
}
//==============
//To get the text of an element (with new lines), you can do this:
document.querySelector("#story").childNodes[0].wholeText;
Maybe something like this? http://jsfiddle.net/DerekL/qv2GZ/
What you shouldn't do is replacing text inside a string and dumping it right into DOM. That's bad practice. That's why here I'm creating a p element instead of replace lines with </p><p>.
I think that you should take a look here:
How do I replace all line breaks in a string with <br /> tags?
And here: How to replace all occurrences of a string in JavaScript?
Remember that new line is simply \n. Then it is a matter of simple string replace. There is a huge research about it, and the question is a possible duplicate, so I think that is enough to answer :).
Best regards!
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().
I want to strip tags from a html, but preserves it's line breaks.
I want the behaviour like copying the text in browser and pasting it in notepad.
For example, a code that converts:
<div>x1</div><div>x2</div> to x1\nx2
<p>x1</p><p>x2</p> to x1\nx2
<b>x1</b><i>x2</i> to x1x2
x1<br>x2 to x1\nx2
Removing all tags not works (/<.*?>/g).
Also creating a dummy <div> and settings it's innertHTML and read it's textContent will remove line breaks.
Any Help?
How's this work for you? This will replace every occurrence of <br>, </div>, and </p> with a \n, and then strip the remaining tags. Its goofy, but its at least a start.
fixed = text_to_fix.replace(/<(?:br|\/div|\/p)>/g, "\n")
.replace(/<.*?>/g, "");
This doesn't work for all HTML, however. Just the tags you mentioned.
Try:
function strip_tags(str){
return str
.replace(/(<(br[^>]*)>)/ig, '\n')
.replace(/(<([^>]+)>)/ig,'');
}
var str = '<div>x1</div><div>x2</div><br>'+'<p>x1</p><p>x2</p>'+'<b>x1</b><i>x2</i>';
This will strip the tags and replace <br /> or <br> with new lines, but adding new lines for block elements requires quite some time to come up with a solution.
Here is a demo