2010-09-30 30 views
1

我有html().replace一個問題:.replace問題

<script type="text/javascript"> 
    jQuery(function() { 
    jQuery(".post_meta_front").html(jQuery(".post_meta_front").html().replace(/\<p>Beschreibung:</p> /g, '<span></span>')); 
}); 
</script> 

什麼是錯在我的腳本?

+0

如果您所描述的問題是什麼這將是一件好事。併發布您的HTML或至少一個簡短的摘錄。 – Strelok 2010-09-30 00:15:52

+0

需要引用正則表達式嗎? – Ascherer 2010-09-30 00:16:15

回答

0

看起來你不是逃避替換函數find參數中的所有特殊字符。你只是逃避了第一個<角色。

試着這麼做:

/\<p\>Beschreibung:\<\/p\>/g 

注意,取而代之的是JavaScript的不是的jQuery的功能。

+0

Thansk Damovisa。你是對的。 – chris 2010-09-30 00:24:03

1

您需要在正則表達式部分轉義正斜槓/

<script type="text/javascript"> 
    jQuery(function() { 
    jQuery(".post_meta_front").html(jQuery(".post_meta_front").html().replace(/<p>Beschreibung:<\/p> /g, '<span></span>')); 
}); 
</script> 
4

你爲什麼用這個正則表達式?

如果要將元素替換爲另一個元素,可以使用jQuery's .replaceWith() method

jQuery(".post_meta_front p:contains('Beschreibung:')") 
               .replaceWith('<span></span>'); 

或者,如果你需要確保內容精確匹配:

jQuery(".post_meta_front p").filter(function() { 
    return $.text([ this ]) === 'Beschreibung:'; 
}).replaceWith('<span></span>'); 
+2

+1。依賴於'html()'輸出的格式根本不可取(不同的瀏覽器會給出不同的文本轉義,元素大小寫和屬性引用格式)。像這樣使用DOM風格的方法更可靠,並且不會不必要地破壞和重新創建所有其他未替換的節點。 – bobince 2010-09-30 00:29:34