David Garcia
David Garcia

Reputation: 2696

Javascript: indexOf

I am using the following code to search for a value in a string.

if (myValue.indexOf("Call") > -1) {
 //dosomething
}

How can I do and or?

(myValue.indexOf("Call" || "Data") > -1)

The following works;

if (myValue.indexOf("Call") > -1 || (myValue.indexOf("Data") > -1) ) {
     //dosomething
    }

But i thought there was an easier way?

Upvotes: 0

Views: 253

Answers (6)

Sachin
Sachin

Reputation: 40970

Try this,

if (myValue.indexOf("Call") > -1  || myValue.indexOf("Data") > -1) {
  //dosomething
}

Upvotes: 2

helder.tavares.silva
helder.tavares.silva

Reputation: 734

I think you can't use indexOf like that.

You either use two separate calls to indexOf

(myValue.indexOf("Call") > -1 || myValue.indexOf("Data") > -1)

Or you can use RegExp

RegExp("Call|Data$").exec(myValue) != null

Upvotes: 1

Chemaclass
Chemaclass

Reputation: 2011

Try this:

var bool = (myValue.indexOf("Call") > -1 ||  myValue.indexOf("Data") > -1);

Upvotes: -1

loxxy
loxxy

Reputation: 13151

This way :

myValue.match(/(Call)|(Data)/ig)

Upvotes: 4

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48683

You can use a regular expression.

String.prototype.regexIndexOf = function (regex, startpos) {
    var indexOf = this.substring(startpos || 0).search(regex);
    return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}

var myValue = 'Lieutenant Commander Data';

if (myValue.regexIndexOf(/(Call)|(Data)/g) > -1) {
    alert('Success');
}

Upvotes: 0

ICeQ
ICeQ

Reputation: 152

Have you tried:

if ((myValue.indexOf("Call") > -1) || (myValue.indexOf("Data") > -1)) {
 //dosomething
}

?

Upvotes: 1

Related Questions