Jquery搜索和替换w/.contains

Jquery搜索和替换w/.contains,jquery,Jquery,我正在尝试搜索并替换为同一单词的所有实例,使用.contains()时不区分大小写,但它似乎不起作用,并且区分大小写。以下是我现在拥有的代码: <p>some text</p> <p>Some Text</p> <p>Some TEXT</p> jQuery.expr[':'].Contains = function(a, i, m) { return jQuery(a).text().toUpperC

我正在尝试搜索并替换为同一单词的所有实例,使用.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"));
        });
一些文本

一些文本

一些文本

jQuery.expr[':'].Contains=函数(a,i,m){ 返回jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase())>=0; }; jQuery.expr[':'].contains=函数(a,i,m){ 返回jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase())>=0; }; $('p').filter(“:contains('some text')”)。每个(函数(){ $(this.text($(this.text().replace(“某些文本”,“替换为新文本”)); });
由于相同的情况,这只会更改第一个文本 您可以在这里查看js fiddle上的示例

实际上,“替换”是区分大小写的。请改用正则表达式:

text().replace(/some text/i,“用新文本替换”)


演示

您包含的内容看起来不错。尝试如下操作,因为使用
.filter
的目的是链接


问题不在于原始匹配,而在于如何替换。即使匹配,replace也没有执行任何操作,因为它的“some text”参数与其他case变量不匹配

然而,我认为这样覆盖jQuery的
:contains
选择器不是一个好主意。使用基于函数的过滤器可以减少代码量,并保持jQuery不变

请参见以下工作示例:


@非常感谢你,凯尔!我想不出如果OP不想替换元素中的所有文本,他可以在返回中编写相同的替换代码。我很喜欢这篇文章,也同意你的观点,我们不应该覆盖jQuery,这是个坏主意。但是我有一个问题,i.test用于什么?
。test
是JavaScript中
RegExp
对象上的一个方法,它针对参数(在本例中为
$(this).text()
)运行正则表达式,并根据匹配与否返回true或false。本例中的
RegExp
对象实际上是一个文本(就像“some string”是一个literal
string
对象):
/some text/i
i
部分告诉它不区分大小写。@ChrissPratt我明白了,谢谢,我还没有学会RegExp,我想这就是为什么我在搜索和替换时遇到麻烦的原因,但是它工作正常,非常感谢
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");
});
$('p').filter(function() {
    return /some text/i.test( $(this).text() );
}).each(function(){
    $(this).text($(this).text().replace(/some text/i, "replace with new text"));
});
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"));
});