Clint
Clint

Reputation: 179

Change new line to <p> wrap in iFrame?

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?

Upvotes: 0

Views: 1582

Answers (2)

skobaljic
skobaljic

Reputation: 9644

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

Upvotes: 1

user2755140
user2755140

Reputation: 2027

I think replacing p by div should fix it. The p tag is tricky.

Upvotes: 0

Related Questions