views:

22328

answers:

4

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?

+23  A: 

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

Paolo Bergantino
+9  A: 

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

cletus
+11  A: 

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; }
eKek0
You have a bug in this implementation: if the searched string starts with txt, it will return false. Use >= instead of >.
Jacob
Corrected for the comment by Jacob
eKek0
A: 

A simple contains can also be useful for example:

<div class="test">Handyman</div>


$(".test:contains('Handyman')").html("A Bussy man");
Plippie