39

Hi I'm new in JavaScript and i find a basic problem:

When I use that piece of code in Python:

'a' in 'aaa' 

I get True

When I do the same in JavaScript I get Error:

TypeError: Cannot use 'in' operator to search for 'a' in aaa

How to get similar result as in Python?

2
  • Another common point of confusion is the is operator in Python which means something totally different in C#. Python is means object identity comparison, C# is is like Python isinstance. Commented May 14, 2015 at 8:11
  • 1
    As a general rule, javascript and Python are quite different; take care with comparison (e.g. use === in javascript), arrays (don't use in to go through a javascript array), dictionaries and objects (separate in Python, same thing in javascript), types (javascript is dynamically and loosely typed, Python is dynamically but strongly typed) and so on. Commented May 14, 2015 at 8:14

5 Answers 5

19

I think one way is to use String.indexOf()

'aaa' .indexOf('a') > -1

In javascript the in operator is used to check whether an object has a property

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

Comments

5

You're looking for indexOf.

'aaa'.indexOf('a') == 0 //if a char exists in the string, indexOf will return
                        // the index of the first instance of the char
'aaa'.indexOf('b') == -1 //if a char doesn't exist in the string, indexOf will return -1

Comments

2

Duplicate (How to check whether a string contains a substring in JavaScript?)

Try this:

var s = "aaaabbbaaa";
var result = s.indexOf("a") > -1;

Comments

2

From MDN:

The in operator returns true if the specified property is in the specified object.

You're interested in 'aaa'.indexOf('a').

Comments

2

try:

if('aaa'.search('a')>-1){
   //
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.