Search code examples
javascriptshorthand-if

Shorthand-if with character index check


I am using a shorthand if statement to check if content has an italic tag in it.

remove = (content.indexOf('<i>') === true) ? true : false;
alert("ORIGINAL CONTENT: " + content + "\nDoes content contain <i>? " + remove);

When that alert pops up, it shows the following: Alert box shows < i > in string, but returns false

What am I doing wrong?


Solution

  • indexOf returns the position of the string inside another string, and -1 if it's not found. It's not like strpos in PHP. So you have to check content.indexOf('<i>') !== -1 instead.

    In your case, I'd simply define

    remove = content.indexOf('<i>') !== -1;
    

    The ternary operator (I used to know that by this name) isn't really necessary here, as the comparison already gives the boolean value you need.