4

I need to get the extension of the URL, for example(.xhtml) using jQuery?

Wazy
  • 8,822
  • 10
  • 53
  • 98
Harry
  • 483
  • 4
  • 10
  • 22

2 Answers2

8

jQuery doesn't come into play here.

If you can guarantee your URL ends with an extension...

var path = window.location.pathname,
    ext = path.substr(path.lastIndexOf('.') + 1);

...or...

var ext = window.location.pathname.split('.').pop();

...otherwise this will return the full path. You could fix that by making it a bit more verbose...

var path = window.location.pathname.split('.'),
    ext;

if (path.length > 1) {
    ext = path.pop();
}
alex
  • 479,566
  • 201
  • 878
  • 984
5

You could take a look at this SO post - it describes how to get the current URL using JQuery. Getting the extension would be relatively simple after that:

$(document).ready(function() {
    var ext = window.location.pathname.split('.').pop();
});

Other SO posts also show how to use the path.

Community
  • 1
  • 1
JW8
  • 1,496
  • 5
  • 21
  • 36