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.

1

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

7 Comments

This looks good, although to completely meet the question's requirements, you should set some class on that <span> and then .css that class to "green" background.
awesome thanks! is there a straightforward way to have var text to be case-insensitive?
@Bruce Good advice. I already did that. I prefer the yellow background color. The OP can change it to green...
for case-insensitive I'd go regex: /my name is (.*)/i
@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.
|
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;

2 Comments

hmm...doesn't seem to work. is the -1 a nodeType? i'm not familiar with this
I believe the claim is that if text() doesn't contain the sub-string "my name is" then .indexOf() will return -1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.