6

HTML:

<p class="greeting">
  hello, my name is kevin. what's yours?
</p>

jQuery:

$("p.greeting").filter(function (){
  return $this.text() === "my name is";
}).css("background", "green");

I'm trying to isolate the words "my name is" in the <p class="greeting"> tag. Can anyone help me with the jQuery as it doesn't seem to work. Thanks.

pruett
  • 2,101
  • 3
  • 22
  • 36

2 Answers2

8

Here you go:

CSS:

.highlight { background-color: yellow; }

JavaScript:

var text = 'My namE iS';

$( 'p.greeting' ).html( function ( i, html ) {
    var regexp, replacement;

    regexp = RegExp( '(' + text + ')', 'gi' );
    replacement = '<span class="highlight">$1</span>';

    return html.replace( regexp, replacement );
});

Live demo: http://jsfiddle.net/SGCDS/5/

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • This looks good, although to completely meet the question's requirements, you should set some class on that and then .css that class to "green" background. – Bruce Oct 31 '11 at 20:14
  • awesome thanks! is there a straightforward way to have `var text` to be case-insensitive? – pruett Oct 31 '11 at 20:17
  • 1
    @Bruce Good advice. I already did that. I prefer the yellow background color. The OP can change it to green... – Šime Vidas Oct 31 '11 at 20:18
  • for case-insensitive I'd go regex: /my name is (.*)/i – Bruce Oct 31 '11 at 20:23
  • @pruett I've updated my answer with a new improved solution (based on regular expressions). The `'gi'` flag ensures that the search is global and case-insensitive. – Šime Vidas Oct 31 '11 at 20:27
  • thanks @ŠimeVidas I don't quite understand everything in your code, but it works great! Time for me to deconstruct what you did :) – pruett Oct 31 '11 at 20:32
  • @pruett Read the MDN pages for [RegExp](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp) and [String.replace](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace). – Šime Vidas Oct 31 '11 at 20:47
1

You're function returns always false. Only if there is exactly "my name is" in your div, it will return true.

Try something like this:

return $(this).text().indexOf("my name is") != -1;
Tobias Golbs
  • 4,586
  • 3
  • 28
  • 49
  • hmm...doesn't seem to work. is the -1 a nodeType? i'm not familiar with this – pruett Oct 31 '11 at 20:09
  • 1
    I believe the claim is that if text() doesn't contain the sub-string "my name is" then .indexOf() will return -1. – Bruce Oct 31 '11 at 20:15