Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'in' operator in JavaScript. String comparison [duplicate]

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?

like image 335
bartekch Avatar asked May 14 '15 08:05

bartekch


People also ask

What is == and === in JavaScript?

The main difference between the == and === operator in javascript is that the == operator does the type conversion of the operands before comparison, whereas the === operator compares the values as well as the data types of the operands.

Can we use == to compare strings in JavaScript?

In JavaScript, strings can be compared based on their “value”, “characters case”, “length”, or “alphabetically” order: To compare strings based on their values and characters case, use the “Strict Equality Operator (===)”.

What is === operator in JavaScript?

The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.

How do I compare two strings in JavaScript?

To compare two strings in JavaScript, use the localeCompare() method. The method returns 0 if both the strings are equal, -1 if string 1 is sorted before string 2 and 1 if string 2 is sorted before string 1.


1 Answers

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

like image 184
Arun P Johny Avatar answered Oct 06 '22 13:10

Arun P Johny