Tuesday, May 3, 2011

jQuery String Contains Manipulation?

In most languages like C# for example given a string you can test (boolean) if that string contains another string, basically a subset of that string.

string x = test2;


if(x.contains("test"))
    // do something

How can I do this in a simple way with Javascript/Jquery?

From stackoverflow
  • This is done with indexOf, however it returns -1 instead of False if not found.

  • The indexOf operator works for simple strings. If you need something more complicated, it's worth pointing out that Javascript supports regular expressions.

  • As Paolo and cletus said, you can do it using indexOf().

    Valid to mention is that it is a javascript function, not a jQuery one.

    If you want a jQuery function to do this you can use it:

    jQuery.fn.contains = function(txt) { return jQuery(this).indexOf(txt) >= 0; }
    
    Jacob : You have a bug in this implementation: if the searched string starts with txt, it will return false. Use >= instead of >.
    eKek0 : Corrected for the comment by Jacob
  • A simple contains can also be useful for example:

    <div class="test">Handyman</div>
    
    
    $(".test:contains('Handyman')").html("A Bussy man");
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.