问题
I am trying to find and replace line breaks in text using javascript.
The following works. It replaces the character a with the character z.
var text = "aasdfasdf";
text= text.replace(/a/g,"z");
alert(text);
The following based on other posts on this and other message boards does not. Basically the javascript does not fire:
var text = "aasdfasdf";
text= text.replace(/\n/g,"z");
alert(text);
...Here is one of many posts that suggests it should work.
JavaScript: How to add line breaks to an HTML textarea?
and by the way following does not work for me in Firefox either:
text = text.replace(/\n\r?/g, '<br />'); or
text = text.replace("\n", '<br />');
Note: I realize there are no line breaks in the text variable..I am just using a simple string for testing purposes.
Can anyone see what could be wrong or show me a way to do this that actually works.
Thanks.
回答1:
I'd cover my bets by handling \r\n
(the sequence), and then handling \r
and \n
through a character class, like this:
text = text.replace(/\r\n/g, '<br />').replace(/[\r\n]/g, '<br />');
The first replace turns the sequence \r\n
into <br />
. The second replace replaces any \r
or \n
characters found on their own with the string.
More on regular expressions in JavaScript here.
回答2:
ECMAScript normalizes line breaks in strings to "\n\r" and the DOM normalizes line breaks in strings to "\n". Both of those OS agnostic which these formats:
- Windows - CRLF
- Unix - LF
- Old Mac - CR
The right way to accomplish this task depends on how you are receiving the string and how you are writing it out.
回答3:
To handle windows new line characters try
text = text.replace(/\r\n/g, '<br />').replace(/[\r\n]/g, '<br />');
回答4:
Another solution for both types of line endings
str.replace(new RegExp('\r?\n','g'), '<br />');
来源:https://stackoverflow.com/questions/13532761/how-do-i-find-line-breaks-and-replace-with-br-elements-in-javascript