pertrai1
pertrai1

Reputation: 4318

stringTo javascript

I am hoping that I can get some help with my learning and find out what it is about my function that is not working correctly:

function contains() {
 var substr = 'bar';
 var str = 'foobar';
  if (str.indexOf(substr)) {
   // Return true if substr is a substring of str
   return true;
  } else {
   // and false if substr is not a substring of str
   return false;
  };
 }

Thank you in advance for anyone who can help me get over this bump in learning.

Rob

Upvotes: 1

Views: 84

Answers (2)

Ya Zhuang
Ya Zhuang

Reputation: 4660

it's kind of off the topic, but you can write some regex like:

function contains() {
    var str = 'foobar';
    var substrRegex = /bar/;
    return substrRegex.test(str);
}

about javascript test(): http://www.w3schools.com/jsref/jsref_regexp_test.asp

about Regex: http://www.regular-expressions.info/

Upvotes: 2

pimvdb
pimvdb

Reputation: 154918

indexOf returns -1 if it's not found, and ~-1 === 0 is falsy. Every other number returns truthy with ~ (since all numbers other than 0 are truthy). ~ is the bitwise NOT which has an interesting property that ~-1 === 0.

!! converts to a boolean (truthy becomes true, falsy becomes false).

So you could do:

function contains() {
  var substr = 'bar';
  var str = 'foobar';
  return !!~str.indexOf(substr);
}

You're currently returning true if it's not found (-1 is thruthy), and false if it's at position 0 (0 is falsy).

Upvotes: 2

Related Questions