1

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

2
  • 3
    str.indexOf(substr) > -1 (if string is not found, return -1) Commented Oct 29, 2011 at 11:48
  • 6
    You can make it shorter: return str.indexOf(substr) > -1;. Commented Oct 29, 2011 at 11:49

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

Comments

2

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.