ATTENTION: You are viewing a page formatted for mobile devices; to view the full web page, click HERE.

Other Software > Developer's Corner

Javascript regular expression to grab filename from URI

(1/2) > >>

I am very new to regular expressions and am struggling with something that I am sure is really pretty straight forward.

I have a string from which I need to return the just the filename, without the extension, or the path, or the serial number (xx = two digits at the start of the filename)

--- Code: Text ---http://website/subdir/xx title of the image.jpg

The top example illustrates the general form of the input text, and the bottom is a real example from the site. The results should be...

--- Code: Text ---title of the imagea very big dog
Other factors...

In theory there may or may not be a subdir.
The %20 should be replaced with spaces (not entirely sure why they are %20s in the first place, but they are!)
The regex flavour is Javascript.

Help appreciated!

Thanks Ampa

Here is how I am doing it without using a regex...

--- Code: Javascript ---var splitArray = this.preLoader.src.replace(/\%20/g, ' ').split('/');var IMGTitle = splitArray[splitArray.length-1];IMGTitle = IMGTitle.substring(3, IMGTitle.length-4);
A bit long winded perhaps?
1) Replace the %20s with spaces.
2) Split the string at the /s and select the last one.
3) Grab the middle of the string.

Would regex be better?

Hi Ampa,

I am not sure if this really helps, since it can't replace the %20.
Nevertheless it replaces the given string with the filename.

--- Code: Javascript ---^.*/\d{2}\s(.*)\..*$$1
In JavaScript this could be done like this:

--- Code: Javascript ---result = subject.replace(/^.*\/\d{2}\s(.*)\..*$/g, "$1");
I think the best solution for the %20 is to replace these using the JavaScript replace command or using a second regular expression.

Hope it helps...


Thanks Marc, I shall try these out  :)

The %20 should be replaced with spaces (not entirely sure why they are %20s in the first place, but they are!)
-Ampa (April 02, 2008, 12:43 PM)
--- End quote ---

Strictly speaking, a URL that's passed to a web server should not have spaces in it (but most browsers and web servers deal with them fine anyway).  You can use javascript's decodeURI() function to convert the %20's (or other encoded characters that might be in the string) to their unencoded form.


[0] Message Index

[#] Next page

Go to full version