Javascript: replacing newlines with <br/> working in FF and SAFARI and not working in IE
Code in the post has been modified.
I was thinking that replacing \n with
with javascript was quite a simple task, but it seems not to be so. Posts in Ask Ben or StackOverflow suggest that something as simple as:var myRe = new RegExp(/\r?\n/g); // to avoid the re literal caching problem
lDes = $("div.descr").html();
lDes = lDes.replace (myRe, "<br/>");
lDes = l开发者_StackOverflow社区Des.replace (/(http:\/\/\S+)/g, "<a target=\"blank\" href=\"$1\">$1</a>");
$("div.descr").html(lDes);
will get the job done. Indeed, this work in FF and Safari but not in IE.
Or, using postie (great hint!)
Text has been created in a textarea and then stored in a database, then retrieved without further processing. It works using FF on windows and Safari on Mac. IE on windows, nada. Is it a major bug in my head? Is it a JQuery issue?
Have some idea about how to solve this? And possible reason for?
Many thanks
Instead of putting the text in question into a <div>
on the page, perhaps you can put it directly into a block of Javascript. Now that will require that you have some server-side code to "protect" the Javascript string constant syntax, which is a strangely rare facility but easy to create. You just have to make sure that quote characters, as well as control characters and characters outside the 7-bit range, are appropriately "escaped" the way Javascript expects string constants to look.
Here's what it'd look like in one of my applications. This is a Java/JSP example, so probably not what you're using, and of course the "escape" function I call is my own invention, but just so you see what I mean:
var theText = '${pointy:escapeJS(data.theText)}';
$('#target').html(theText.replace(/\n/g, '<br>'));
Of course if you're receiving the text as an AJAX response, things are simpler.
Now that example leaves out something important: you have to make sure the text is HTML-escaped before dropping it into the document. Perhaps that's been done server-side, or if not you can do that in Javascript too:
$('#target').html(theText
.replace(/\r/g, '') // get rid of carriage returns
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\n\n/g, '\n \n')
.replace(/\n/g, '<br>')
);
(There are better/faster ways to do HTML escaping of course; that's just an example.) Note that I stick explicit blank padding between successive newlines - that's something I cribbed from some code I have and I think I did that because successive <br>
elements without intervening "stuff" might not give multiple blank lines in the result; not sure however.
What DOCTYPE are you using? It may be that, depending on the DOCTYPE (i.e., not using XHTML), <BR/>
should be rendered as <BR>
. IE could be in some weird state of compatibility or quirks mode, etc.
精彩评论