How do you preserve the line breaks in a textarea

2019-02-19 14:21发布

问题:

I know that my question is very similar to this one: jQuery text() function loses line breaks in IE, but my needs are slightly different.

I have a textarea on my page that has a "template" string of text to be inputted by the user. (It lets them write a message, using %NAME% as a place holder for the name.)

After the user finishes the "template", I put it into a second textarea that actually replaces %NAME% with whatever name should be used. I've got that part of the function covered, and it works perfectly.

The second part works fine in most browsers, too.

However, in Internet Explorer, the line breaks from the first textarea are not preserved to the second. So for example, if the user entered into the first box:

Hi %NAME%,
How are you?

And the name to replace the text was "Zak", the second box would display as:

Hi Zak,How are you?

My code to get the text into the second box is:

var inviteTemplate=$('#invitationTemplate').text();
inviteTemplate=inviteTemplate.replace(/%NAME%/g,name);
$('#invitationText').html(inviteTemplate);

I'm assuming that the problem is with using .text() to get the contents of the textarea. Is there any way that I can make IE preserve the line breaks into the second textarea?

回答1:

I can confirm that in IE9 beta, you can transfer the text from one TEXTAREA element to another TEXTAREA element with the line-breaks preserved.

Live demo: http://jsfiddle.net/LWjP6/1/



回答2:

You are reading the data as text and writing it as HTML. Have you tried substituting the newline characters by HTML BR tags? e.g.

inviteTemplate = inviteTemplate.replace(/\n/g, '<br>');

I'm pretty sure that will do what you want.