Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Search and Replace w/ .contains

Tags:

jquery

I am trying to do a search and replace with all instances of the same word, having not be case sensitive by using .contains () but it seems that it is not working and is case sensitive. Here is the code of 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, because of the same case you can look at the example on js fiddle here http://jsfiddle.net/ka82V/

like image 203
Kevin Avatar asked May 07 '12 20:05

Kevin


1 Answers

It's actually 'replace' that was case sensitive. Use a regex instead:

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

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

like image 199
Kyle Macey Avatar answered Oct 05 '22 23:10

Kyle Macey