38

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?

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
bartekch
  • 603
  • 8
  • 15
  • 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`. – Kos May 14 '15 at 08: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. – Phil H May 14 '15 at 08:14

5 Answers5

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
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
Zaenille
  • 1,384
  • 9
  • 16
2

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

Try this:

var s = "aaaabbbaaa";
var result = s.indexOf("a") > -1;
Community
  • 1
  • 1
suvroc
  • 3,058
  • 1
  • 15
  • 29
2

From MDN:

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

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

Kos
  • 70,399
  • 25
  • 169
  • 233
2

try:

if('aaa'.search('a')>-1){
   //
}
Yangguang
  • 1,785
  • 9
  • 10