View Full Version : indexOf

02-02-2004, 02:42 PM
I have written a bit of code that is checking the file extension.

I do a substring from the indexOf(".") but of course that is grabbing the first dot.

Is there a function grans the last occurense of a dot or a Regular expression that can retrieve the file extension?

TIA Dale

02-02-2004, 02:56 PM
This regex: /\.([^.]+)$/ will match a fullstop, followed by capturing one or more characters that are not fullstops, followed by end of string. The result of executing /\.([^.]+)$/.exec([string FileName]) will result in a regex array [entirematch, justthefileextention]. entirematch will of course contain the fullstop while justthefileextention will not, but that's the only difference.

Jeff Mott
02-02-2004, 03:13 PM
Is there a function grans the last occurense of a dotlastIndexOf (http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/string.html#1197005)

Almost certainly more efficient than a regexp would be (despite how little it would matter.
var fn = "filename.ext";
var ext = fn.substr( fn.lastIndexOf(".") + 1 );

02-02-2004, 03:16 PM
Ok thanks for that.
I noticed though, if there are no "." then there is no array returned. So I guess I need to check that.

How can I include characters that I dont want to allow, in particular at the moment, ""


02-02-2004, 03:22 PM

Jeff Mott is probably right about the lastIndex thing, though. It is more effective than a regex, except for possibly a single character regex matching only fullstop, which you could use with the split method of a string. (Regex are compiled before command execution, so they are more effective at fixwidth searching than the string comparisons are.)

02-02-2004, 03:34 PM
Ok, I think Im gonna use a bit of both.

Im getting the extension part using lastindexOf

I want to do a check that the whole path doesn't contain a "" or a "@"

How can I write a regEx to do this, I little explanation of what each bit of the regEx does would be really useful


02-02-2004, 03:41 PM
In my sig, there are two links to an article about regex in JavaScript that I wrote three years ago. It is, if I may say if myself, the best regex reference/tutorial you will find for JavaScript. It may be of service for you, so do read it. If you still need help, you can find me here, though.