开发者

Moving data back and forth between p and textarea, but preserving linebreaks

This should be a simple one for someone who gets regex.

I ha开发者_运维问答ve a field on a page that is pre-populated by php, but is editable using javascript. I need to be able to preserve linebreaks when swapping between 'edit mode' and 'fixed mode'.

I understand that textareas like their linebreaks to be \n, and normal html likes to see <br /> tags. I'm using the function .replace(/\n/g, '<br />') to get from textarea to div, but I'm not sure what to use to get the field back into the textarea and keep the linebreaks.

Also I'm not sure whether just replacing <br /> with \n is safe, in case the browser decides it likes <br> better.


When you set white-space: pre-wrap in CSS then the line breaks are preserved with no need to replace them with br tags.

See this example: http://jsfiddle.net/jVBdm/

Update: white-space: pre-wrap will not work in IE6 and IE7 (thanks Kenneth J for pointing this out) but white-space: pre will work — which may or may not be enough for you. You can use a conditional style for IE6 and IE7 to use pre and use use pre-wrap on modern browsers.


It does not really matter whether you use <br /> (xhtml) or <br> browsers should parse them exactly the same.

I think you would use the same break tag you inserted.

To be safe, I suppose you could just do both.

txt =  txt.replace(/<br \/>|<br>/gi, '\n')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜