Change new line to <p> wrap in iFrame? - javascript

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.

Related

New line that is visible in both HTML and console.log

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}.

Can I insert some string at every other line using javascript?

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!

How to preserve whitespace in dynamically added javascript DOM element without using CSS?

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

Edit HTML with javascript: Insert \n instead of <br> as a new line

I am using this code to insert a new line in a content editable HTML document:
execCommand("insertHTML", false, '\n');
This works for me in Chrome and Safari, but it results in < br> or a new paragraph in other browsers. Because I am editing < pre> tags, I do not want the browser to change \n to a < br>. How can I do this?
I have already tried to use functions like range.insertNode() or to manipulate insertBrOnReturn in FireFox, but it is always the same. Isn't there a way to insert a \n in the document without the browser changing my input?
I think there is no cross-browser working way to add a \n... I am not THAT familiar with contenteditable but since it is changing the innerHTML you could maybe do something like
var currentContent = myContent; // "currentContent holds" the current content
execCommand("insertHTML", false, '\n'); // inserts the line break
if (newContent !== currentContent + '\n') { // "newContent" holds the content afterwards
console.log('use String.prototype.replace to replace created tag with "\n"');
}
I'm assuming that you want to save the edited content afterwards, so how about replacing all <br>s with \ns when getting the content of the tag? Just like this:
document.getElementById("editable").innerHTML.replace(/<br>/g, "\n");
edit: You may also just use the innerText instead of the innerHTML. When doing so, all newlines are presented as <br> tags (at least I got that result in Chrome). This solution isn't great, but it's at least always the same.

Read each line of an element in jQuery

Suppose I have this html markup:
<div id="wrapper">
<pre class="highlight">
$(function(){
// hide all links except for the first
$('ul.child:not(:first)').hide();
$("a.slide:first").css("background-color","#FF9900");
$('ul.parent a.slide').click(function(){
$('ul.parent a.slide').css("background-color","#3399FF");
$('ul.parent a.slide').mouseout(function(){
$(this).css("background-color","#3399FF");
});
$('ul.parent a.slide').mouseover(function(){
$(this).css("background-color","#66CC66");
});
});
});
</pre>
</div>
What is the easiest way to read each line of code present in the div. How do I extract each line of code from that div or loop over each line styling in any way I want.
Edit:
I have added the pre tag after the wrapper class, please consider that also.
Do you mean something like this:
var lines = $("#wrapper pre").text().split("\n");
$.each(lines, function(n, elem) {
console.log(elem);
});
Since this is text (and not html) you should treat it as such. The only way to do it is to read it and then use string parsing routines.
Mostly just need straight JavaScript:
var text;
text = $('#wrapper pre').text(); // Or .html, doesn't really matter with the input you showed
text = text.replace("\r\n", "\n"); // Just in case
text = text.split("\n");
// text is now an array of lines
Some browsers will trim the first line break, some won't, so there are a couple of edge cases (no pun). But that's basically it.

Categories

Resources