views:

287

answers:

5

Does Javascript or jQuery have sometime like the "in" statement in Python?

"a" in "dea" -> True

Googling for the word in is hopeless :(

+11  A: 

It does have an in operator but is restricted to object keys only:

var object = {
    a: "foo",
    b: "bar"
};

// print ab
for (var key in object) {
    print(key);
}

And you may also use it for checks like this one:

if ("a" in object) {
    print("Object has a property named a");
}

For string checking though you need to use the indexOf() method:

if ("abc".indexOf("a") > -1) {
    print("Exists");
}
Ionuț G. Stan
Why was this downvoted? It's the only answer that actually answers the question..?
peirix
The question is about finding a string within a string.
Matt Grande
Aha. I don't know Python, so I read the question to be about the `in` statement in javascript. Makes sense now.
peirix
@Matt Grande, that doesn't mean we shouldn't tell him about the in operator.
Ionuț G. Stan
+1  A: 

How about indexOf?

mgroves
+2  A: 

Sounds like you need regular expressions!

if ("dea".match(/a/))
{ 
    return true;
}
Matt Grande
That's using a sledgehammer to put up a picture hook. Use indexOf.
David Dorward
"dea".test(/a) is more efficient in that context as it just returns true or false directly, eliminating the overhead of constructing a match object and then working out if it's null or not to derive true or false before throwing it away.
NickFitz
Also, what @DavidDorward said ;-)
NickFitz
Good to know about the test method, thanks. Also, is indexOf noticeably faster than RegEx in this case? I find matching true/false easier to read than checking if it's greater than -1.
Matt Grande
+5  A: 

you would need to use indexOf

e.g

"dea".indexOf("a"); will return 2

If its not in the item then it will return -1

I think thats what you are after.

AutomatedTester
A: 

With the indexOf function, you can extend the String like such:

String.prototype.in = function (exp) {
    return exp.indexOf(this) >= 0;
}

if ("ab".in("abcde")) { //true

}
Andreas Grech
And people accused ME of using a sledgehammer to put up a picture hook... :P
Matt Grande
haha well I still used indexOf, not regExp ;P ...i just made it easier to use
Andreas Grech
I'd rather make a String.prototype.contains(substring) method. Anyway, nice idea.
Ionuț G. Stan
I used "in" to conform to the OP's original request
Andreas Grech