1

When verifying that character is NOT in string, is it both the same when using if(string.indexOf("x") < 0) { ... } or if(string.indexOf("x") == -1) { ... }?

Could there be some circumstances when string.indexOf("x") would be -2 or lower?

Thank you for sharing your experiences.

2
  • 1
    No, It will always be -1 if sub string not found in the string. There is no chance to return values below that. Commented Apr 11, 2016 at 13:08
  • The indexOf() method returns the position of the first occurrence of a specified value in a string. This method returns -1 if the value to search for never occurs. w3schools.com/jsref/jsref_indexof.asp Commented Apr 11, 2016 at 13:09

3 Answers 3

2

Could there be some circumstances when string.indexOf("x") would be -2 or lower?

No. It cannot. Index is negative (-1) only when there is no match.

When verifying that character is NOT in string, is it both the same when using if(string.indexOf("x") < 0) { ... } or if(string.indexOf("x") == -1) { ... }

Of course they are the same because -1<0.

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

Comments

2

According to indexOf() specification, it can return a value: -1 (if substring not found) and from 0 up to string.length - 1 (indicating the match position).


A better approach is to use the ECMAScript 6 method includes():

var string = 'x-files';

string.includes('x'); // prints true

Comments

1

They are the same:

"The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present."

MDN

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.