2010-01-10 66 views
2

嘿,我試圖取代在JavaScript換行符替換不工作:(

<blockquote>...</blockquote> 

>> ... 

這是我的代碼:

var testhtml = 'sdkjhfbs <blockquote>skldfjsfkjghbs\n sdjkfhb ksdbhv isl\n kdjbhdfgkj bs</blockquote>kdjfgnkdfj'; 
alert(blockquoteConvert(testhtml)); 

function blockquoteConvert(html) { 
    return '>>' + html. 
     replace(/<blockquote>([^]+)<\/blockquote>/gi,"$1"). 
     replace('/\n/','\n>> '); 
} 

但它沒有找到Linebreaks(我用indexOf('\ n')查過)

我該怎麼做?

回答

7

嘗試沒有引號:

replace(/\n/g,'\n>> ') 

現在分隔符是字面正則表達式聲明語法的一部分,而不是模式本身的一部分。

0

使用雙反斜槓\\n應該有所幫助。

+0

和RegExp對象也會。 ''abc \ ndef'.replace(new RegExp('\\ n','g'),'\ n >>')' – ZJR 2010-01-10 15:13:57

0

您需要進行全局替換,否則替換將僅匹配第一個換行符。此外,您不能使用在你的正則表達式的報價爲斜槓將成爲搜索字符串的一部分,所以試試這個:

replace(/\n/g,'\n>> ') 
0

你接近,但你不在家的語法一致:

function blockquoteConvert(html) { 
    return '>> ' + html. 
     replace(/<blockquote>([^]+)<\/blockquote>/gi,"$1"). 
     replace(/\n/g,'\n>> '); 
} 
0

試試這個

var testhtml = 'sdkjhfbs <blockquote>skldfjsfkjghbs\n sdjkfhb ksdbhv isl\n kdjbhdfgkj bs</blockquote>kdjfgnkdfj'; 
alert(blockquoteConvert(testhtml)); 

function blockquoteConvert(id) { 
car text = document.getElementById(id).value; 
text = text.replace(/\n\r?/g, '>>'); 
} 


Or use jquery 
$('#caption').html($('#caption').text().replace(/\n\r?/g, '>>')); 
0

好了,現在我很困惑。試試這個請:

var testhtml = 'sdkjhfbs <blockquote>skldfjsfkjghbs\n sdjkfhb ksdbhv isl\n kdjbhdfgkj bs</blockquote>kdjfgnkdfj'; 
alert(convertLineBreaks(testhtml)); 
alert(blockquoteConvert(testhtml)); 

function blockquoteConvert(html) { 
    return html 
     .replace(/<blockquote>([^]+)<\/blockquote>/gi,convertLineBreaks("$1")); 
} 

function convertLineBreaks(text) { 
    return '>>' + text.replace(/\n/g,'\n>> '); 
} 

更換塊引用後,我換行似乎失去了......?