2012-05-07 45 views
5

我想做一個搜索並用相同的單詞的所有實例替換,並沒有通過使用.contains()大小寫敏感但它似乎不工作,並且是大小寫敏感。這裏是什麼,我現在有代碼:jquery搜索和替換w/.contains

<p>some text</p> 
<p>Some Text</p> 
<p>Some TEXT</p> 


jQuery.expr[':'].Contains = function(a, i, m) { 
     return jQuery(a).text().toUpperCase() 
      .indexOf(m[3].toUpperCase()) >= 0; 
     }; 
     jQuery.expr[':'].contains = function(a, i, m) { 
     return jQuery(a).text().toUpperCase() 
      .indexOf(m[3].toUpperCase()) >= 0; 
     }; 


     $('p').filter(":contains('some text')").each(function(){ 
      $(this).text($(this).text().replace("some text", "replace with new text")); 
     }); 

這僅改變第一個文本,因爲相同的情況下 你可以看看在這裏JS騙取錢財的例子 http://jsfiddle.net/ka82V/

回答

1

的問題是不是與原來的匹配,但如何你更換。即使確實與相匹配,替換也不會執行任何操作,因爲它的「某些文本」參數與其他案例變體不匹配。

但是,我不認爲這是重寫jQuery的:contains這樣的選擇器是個好主意。使用基於函數的過濾器會減少代碼,並保持jQuery不變。用於指出該問題的根本原因http://jsfiddle.net/Y6bhS/1/

$('p').filter(function() { 
    return /some text/i.test($(this).text()); 
}).each(function(){ 
    $(this).text($(this).text().replace(/some text/i, "replace with new text")); 
}); 
+0

我喜歡這個,並且同意你的觀點,我們不應該重寫jQuery,這是一個壞主意。但有一個問題,i.test是什麼? – Kevin

+0

'.test'是JavaScript中RegExp對象的一種方法,它針對參數(在本例中爲$(this).text()')運行正則表達式,並根據它是否匹配返回true或false 。在這種情況下'RegExp'對象實際上是一個文字(就像「some string」是一個文字'String'對象):'/ some text/i'。 'i'部分告訴它不區分大小寫。 –

+0

@ChrissPratt我看到謝謝,我還沒有學到RegExp,但我想這就是爲什麼我在搜索和替換時遇到麻煩,但是它的工作,非常感謝 – Kevin

2

它實際上是「取代'這是區分大小寫的。使用正則表達式來代替:

text().replace(/some text/i, "replace with new text"));

DEMOhttp://jsfiddle.net/ka82V/1/

+0

1:

參見在工作示例。 –

+0

@KyleMacey +1非常感謝你凱爾!我無法弄清楚 – Kevin

2

您包含看起來不錯。試着像下面爲使用.filter的目的是鏈

DEMO

jQuery.expr[':'].containsCI = function(a, i, m) { 
    return jQuery(a) 
     .text() 
     .toUpperCase() 
     .indexOf(m[3].toUpperCase()) >= 0; 
}; 

$('p').filter(":containsCI('some text')").text(function() { 
    return $(this).text().replace(/some text/i, "replace with new text"); 
}); 
+0

如果OP不想替換元素中的所有文本,該怎麼辦? –

+0

@KyleMacey他可以在返回內寫入相同的替換代碼。更新的原因是這是他原來的帖子。 –

1
jQuery.expr[':'].Contains = function(a, i, m) { 
    return new RegExp(m[3], 'ig').test(jQuery(a).text()); // case insensitive replace 
}; 
jQuery.expr[':'].contains = function(a, i, m) { 
    return new RegExp(m[3], 'ig').test(jQuery(a).text()); // case insensitive replace 
}; 

$('p').filter(":contains('some text')").each(function() { 
    $(this).text($(this).text().replace(new RegExp($(this).text(), 'i'),"replace with new text")); 
});