2010-02-08 61 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 />')