views:

1879

answers:

5

Hi,

I have a url like http://www.example.com/blah/th.html

I need a javascript function to give me the 'th' value from that.

All my urls have the same format (2 letter filenames, with .html extension).

I want it to be a safe function, so if someone passes in an empty url it doesn't break.

I know how to check for length, but I should be checking for null to right?

+3  A: 

How To Get URL Parts in Javascript.

"This JavaScript Tutorial article explains the Location object, and how to retrieve the URL from it in several parts, including how to parse, split, and rebuild URLs."

Jonathan Sampson
A: 
<script type="text/javascript">
function getFileName(url){
  var path = window.location.pathName;
  var file = path.replace(/^.*\/(\w{2})\.html$/i, "$1");
  return file ? file : "undefined";
}
</script>
roenving
+2  A: 

Use the match function.

function GetFilename(url)
{
   if (url)
   {
      var m = url.toString().match(/.*\/(.+?)\./);
      if (m && m.length > 1)
      {
         return m[1];
      }
   }
   return "";
}
David Morton
A: 

Using jQuery with the URL plugin:

var file = jQuery.url.attr("file");
var fileNoExt = file.replace(/\.(html|htm)$/, "");
// file == "th.html", fileNoExt = "th"
Chase Seibert
A: 

Similar to the others, but...I've used Tom's simple script - a single line,
then you can use the filename var anywhere:
http://www.tomhoppe.com/index.php/2008/02/grab-filename-from-window-location/

var filename = location.pathname.substr(location.pathname.lastIndexOf("/")+1,location.pathname.length);
brandonjp