Tomek Buszewski
Tomek Buszewski

Reputation: 7935

Check for an array element in a string

I've been doing "check string in array", but never the oposite. And that's what I need now. Currently I have this:

var Hash = 'http://example.com/place/england,
    arr = ['/place/'];

if(Hash.indexOf(arr)) {
    alert('it is')
} else {
    alert('it is not')
};

Problem is, it always returns true (alerts it is). Where I go wrong here?

Upvotes: 0

Views: 55

Answers (3)

Amadan
Amadan

Reputation: 198324

indexOf returns -1 when not found, 0...n-1 on found. Thus, you are saying it is when ['/place/'].toString() (which evaluates to /place/) is not at the start of the string; you will get it is not only if it was found at the nullth position.

Instead, you want to test for -1. Also, if you want to test for all elements of the array instead of the concatenation of the array (because, if arr = ['/place/', '/time/'] you would end up searching for the string "/place/,/time/"), you want to do something else, like iteration or regular expression.

// iteration (functional style)
var found = arr.some(function(element) { return Hash.indexOf(element) !== -1; });

or

// regular expression approach
function escapeRegExp(string){
  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
var pattern = new RegExp(arr.map(escapeRegExp).join('|'));
var found = pattern.test(Hash);

(escapeRegExp from MDN)

Upvotes: 1

user2575725
user2575725

Reputation:

You need to loop through the array to compare. Second thing your condition is not written in desired way.

if(Hash.indexOf(arr)) 

.indexOf() gives -1 for not found else > -1. In js 0 is false and other numbers are true hence you always get the true alert.

var Hash = 'http://example.com/place/england',
  arr = ['/place/'];
var i = arr.length;
while (i--)
  if (-1 < Hash.indexOf(arr[i]))
    alert('found, ' + arr[i]);
  else
    alert('not found, ' + arr[i]);

Upvotes: 1

MrCode
MrCode

Reputation: 64526

Well String.prototype.indexOf only accepts a string as an argument, and you're passing it an array. Either access the first element of the array, to get the string, or loop over the whole array if it could have more than one element.

if(Hash.indexOf(arr[0])) {
//                 ^^^ access first element

Or loop the whole array:

for(var i=0; i<arr.length; i++){
    if(Hash.indexOf(arr[i])) {
        alert('it is')
    } else {
        alert('it is not')
    };
}

Upvotes: 0

Related Questions