2010-02-08 62 views
8

我有一个字符串,其中包含一个字符串(13)作为linebreak。我如何用例如替换它。 <br>?我试过mystring.replace("\n","<br>");但它没有工作javascript:替换linebreak

在此先感谢。

+0

Dupe:http://stackoverflow.com/questions/784313/read-line-break-in-a-string-with-javascript – 2010-02-08 23:11:47

+0

将分行符分配给变量不是更简单吗? – 2012-06-04 04:03:49

回答

29

"\n"是chr(10)。我想你想要"\r"

mystring.replace("\r", "<br>"); 

更新时间:更换所有\ r使用正则表达式:

mystring.replace(/\r/g, "<br>"); 

如果你希望它与Windows,Unix和Mac工作样式换行符使用此:

mystring.replace(/\r?\n|\r/g, "<br>"); 
+0

是,chr(13)是'\ r',而不是'\ n'。 – 2010-02-08 22:56:38

+0

好消息 - 它的工作。但不幸的是只有第一次换行(我的字符串中有几个)。有任何想法吗? – Fuxi 2010-02-08 22:58:37

+0

你需要在我的回答中使用正则表达式中的g标志,并且不仅要考虑\ r而且\ n – Mic 2010-02-08 22:59:52

7
theString.replace(/\n|\r/g, '<br />')