Reputation: 1910
I think that it is obvious what my code does.
Why does my code return a whole string if I use the !==
operator? I know that arrays in Javascript start from at index 0
, and here I'm entering the whole filename as the argument, so indexOf(".")
will always be greater then 0
. No, I'm not passing an .htaccess file here.
function getFileExtension(i) {
// return the file extension (with no period) if it has one, otherwise false
if(i.indexOf(".") !== 0) { //
return i.slice(i.indexOf(".") + 1, i.length);
} else {
return false;
}
}
// here we go! Given a filename in a string (like 'test.jpg'),
getFileExtension('pictureofmepdf'); return given string
// both operand are same type and value
But if I change comparasion to
(i.indexOf(".") > 0) // logs false
P.S. I case that you are asking, this is form usvsth3m.
Upvotes: 0
Views: 113
Reputation: 1910
Well, to simplify, I omit that indexOf returns index which is typeof number, or -1, not returning boolean value FALSE in case when given value not found. So in case of comparing -1 to 0, result is true, and that's why I actually geting outputed given string, instead false. Well, MDN is in my bookmark bar now
var z = -1;
console.log(z >= 0); // evaluates false because -1 < 0
console.log(z !== 0); // evaluates true because -1 !== 0
// also if z > 0 it is !== 0, but could be < 0
So next code works like a charm.
function getFileExtension(i) {
// i will be a string, but it may not have a file extension.
// return the file extension (with no period) if it has one, otherwise false
if(i.indexOf(".") >= 0) {
return i.substring(i.indexOf(".") + 1, i.length);
} else {
return false;
}
}
getFileExtension('pictureofmepdf');
Upvotes: 1
Reputation: 7521
indexOf()
returns the index of the substring, so it can return 0
, which would mean that the substring appears at position 0
. If the substring is not found, it returns -1
instead, so change your if
statement to reflect this logic:
if(i.indexOf(".") >= 0)
Additionally, you should use substring()
to extract a substring from a string - slice()
is for arrays.
return i.substring(i.indexOf(".") + 1, i.length);
Still, I think a better way to do this is with split()
:
var fileNameArray = i.split("."); // "foo.txt" --> ["foo" "txt"]
if(fileNameArray.length >= 2) {
return fileNameArray[1];
} else {
return false; //maybe you want to return "" instead?
}
Upvotes: 2
Reputation: 733
The String method indexOf
returns (if it is founded) the first index of the string you search, and remember, index can be zero, that why you have to do a strict comparision to check if indexOf
it is not returning a boolean false.
I will suggest you to use lastIndexOf
for this case because a file named as something.min.js
will return min.js
as an valid extension, and nope.
Upvotes: 2