开发者

How can I replace newline characters using javascript in IE8?

I've searched Stackoverflow for hours and hours, and nobody's solution works in Internet Explorer 8.

I am provided with a plaintext document like this:

This is a legal agreement ("Agreement") between you and ...
License
Subject to you continued and ongoing compliance with the terms and conditions set ...
Restrictions
Except as otherwise explicitly provided in this Agreement, ...
Ownership
Except for this license granted to you, as between you and ...
Disclaimer of Warranties
Use at your own risk. ...

And I need to replace the newline characters (linebreaks, carriage returns, whatever you want to call them) with double linebreaks (<br/><br/>) to make the text look more normal.

The nl2br function from jQuery convert line breaks to br (nl2br equivalent) works fine in most browsers. However, a client of mine uses IE8.

Go ahead and try the nl2br function using IE8 (or a modern Internet Explorer set to IE8 mode); 开发者_Go百科it doesn't work.

Does anyone know why it doesn't work in IE8? And how to accomplish the goal?

P.S. I put some code here http://jsfiddle.net/L2Ufj/2/ and oddly enough it works in IE8 via jsfiddle, but if you copy it to somewhere else and run it for real, it won't work in IE8.


One way to get round this in IE8 is to convert the line-breaks into a 'token' that IE8 will recognise before it is rendered on the page. Then once it's rendered, in a success handler for example you can search for that token and replace with <br> or whatever you wish:

e.g.

Pre render (I've used < br > as my token but you can use anything)

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

Post render (Search for your token and replace with <br> or whatever you wish)

renderedTextWrapper.innerHTML = renderedTextWrapper.innerHTML.replace(/&lt;br&gt;/g, '<br>');


When you retrieve element's innerHTML, IE will convert the innerHTML to a "standard-format" (by collapsing multi-spaces into one, removing linebreak, etc...) before giving you the result.

Thus, you can not find any linebreak character in the innerHTML you get with IE. What a bad news.

I think the most feasible & easy approach is to store your text inside <textarea> tag instead of normal <div>. IE will leave <textarea> alone when you get it's value instead of innerHTML:

originalText=document.getElementById('EULA_content').value

Of course, when you get the newText, you should append it to another div element.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜