Question

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?

Était-ce utile?

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

Autres conseils

Mostly covered in other answers, but in:

> content.indexOf('<i>') === true

note that String.prototype.intexOf returns a Number and it is being compared to a Boolean. Since they are different Types, the result will always be false. If the equals operator "==" had been used, it would return true if the left hand expression returned any value other than zero (0).

Incidentally, italic text can be implemented using elements other than I, e.g. a span element with suitable styling applied through CSS.

Have you considered using Regex?

remove = /<i>/.test(content);

Thanks RobG for the correction.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top