4

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

"a" in "dea" -> True

Googling for the word in is hopeless :(

5 Answers 5

29

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");
}
Sign up to request clarification or add additional context in comments.

4 Comments

Why was this downvoted? It's the only answer that actually answers the question..?
The question is about finding a string within a string.
Aha. I don't know Python, so I read the question to be about the in statement in javascript. Makes sense now.
@Matt Grande, that doesn't mean we shouldn't tell him about the in operator.
6

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.

Comments

2

Sounds like you need regular expressions!

if ("dea".match(/a/))
{ 
    return true;
}

4 Comments

That's using a sledgehammer to put up a picture hook. Use indexOf.
"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.
Also, what @DavidDorward said ;-)
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.
1

How about indexOf?

Comments

1

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

}

4 Comments

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

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.