Finding and replacing jquery w / .contains

I am trying to search and replace all instances of the same word without being case sensitive using .contains (), but it seems to not work and is case sensitive. Here is the code for what I have now:

<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"));
        });

This only changes the first text due to the same case, you can see an example on js fiddle here http://jsfiddle.net/ka82V/

+5
source share
4 answers

The problem is not in the original comparison, but in how you changed. Even if it corresponded, the substitute did nothing, because the argument "some text" does not correspond to other variants of the case.

, , 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"));
});
+1

"", . :

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

DEMO http://jsfiddle.net/ka82V/1/

+2

You have a good looking. Try using below as the purpose of use .filteris chaining

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");
});
+2
source
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"));
});
+1
source

All Articles