176

In Java, given a java.net.URL or a String in the form of http://www.example.com/some/path/to/a/file.xml , what is the easiest way to get the file name, minus the extension? So, in this example, I'm looking for something that returns "file".

I can think of several ways to do this, but I'm looking for something that's easy to read and short.

Cwt
  • 8,206
  • 3
  • 32
  • 27
Sietse
  • 7,884
  • 12
  • 51
  • 65
  • 3
    YOU do realize there is no requirement for there to be a filename at the end, or even something that looks like a filename. In this case, there may or may not be a file.xml on server. – Miserable Variable Mar 03 '09 at 09:47
  • 2
    in that case, the result would be an empty string, or maybe null. – Sietse Mar 03 '09 at 09:57
  • 1
    I think you need to define the problem more clearly. What about following URLS endings? ..../abc, ..../abc/, ..../abc.def, ..../abc.def.ghi, ..../abc?def.ghi – Miserable Variable Mar 03 '09 at 10:10
  • 3
    I think it's pretty clear. If the URL points to a file, I'm interested in the filename minus the extension (if it has one). Query parts fall outside the filename. – Sietse Mar 03 '09 at 10:29
  • The client has no means of knowing if the server uses a file! – Miserable Variable Mar 03 '09 at 13:18
  • You haven't precisely defined what you mean by a "file name" or an "extension" - and no, those aren't terms that everyone understands in the same way. – James Moore May 22 '12 at 16:17
  • 4
    the file name is the part of the url after the last slash. the file extension is the part of the file name after the last period. – Sietse Jun 12 '12 at 10:59
  • You might be able to do this using the Apache Commons IO FilenameUtils class. See answer provided by slashnick: http://stackoverflow.com/questions/8393849/how-to-get-name-of-file-object-without-its-extension-in-java – Spoonface Nov 22 '12 at 22:41
  • 1
    Related: http://stackoverflow.com/questions/4050087/how-to-obtain-the-last-path-segment-of-an-uri (Contains the best answer, no dependencies, but does not accomplish goal of removing extension.) – Jason C May 06 '15 at 20:31

29 Answers29

227

Instead of reinventing the wheel, how about using Apache commons-io:

import org.apache.commons.io.FilenameUtils;

public class FilenameUtilTest {

    public static void main(String[] args) throws Exception {
        URL url = new URL("http://www.example.com/some/path/to/a/file.xml?foo=bar#test");

        System.out.println(FilenameUtils.getBaseName(url.getPath())); // -> file
        System.out.println(FilenameUtils.getExtension(url.getPath())); // -> xml
        System.out.println(FilenameUtils.getName(url.getPath())); // -> file.xml
    }

}
Nick Grealy
  • 24,216
  • 9
  • 104
  • 119
Adrian B.
  • 4,333
  • 1
  • 24
  • 38
  • 2
    In version commons-io 2.2 at least you still need to manually handle URLs with parameters. E.g. "http://example.com/file.xml?date=2010-10-20" – Luke Quinane Aug 13 '13 at 05:14
  • yes @LukeQuinane this doesn't seem to handle the urls with query params :( – Sebastien Lorber Apr 18 '14 at 12:37
  • 18
    FilenameUtils.getName(url) is a better fit. – ehsun7b Apr 22 '14 at 06:05
  • 4
    It seems odd to add a dependency on commons-io when easy solutions are readily available just using the JDK (see `URL#getPath` and `String#substring` or `Path#getFileName` or `File#getName`). – Jason C May 06 '15 at 20:31
  • 2
    I see this solution referenced everywhere when it doesn't solve the problem of dealing with querystrings. – Marc Jun 30 '15 at 14:34
  • 6
    The FilenameUtils class is designed to work with Windows and *nix path, not URL. – nhahtdh Jul 29 '15 at 09:22
  • by default we can't use it, we must import a library... `compile 'commons-io:commons-io:2.4'` for Gradle and ` commons-io commons-io 2.4 ` for maven – Choletski Oct 22 '15 at 07:30
  • 4
    Updated example to use a URL, show sample output values and use query params. – Nick Grealy Oct 28 '16 at 04:12
  • FilenameUtils.getName can return unwanted results at times. [More information here, in another answer on this page](https://stackoverflow.com/a/41244248/26510) – Brad Parks Jan 22 '18 at 20:06
  • This solution does not takes content-disposition header into account, which needs to make a request to the URL. – djmj Jan 29 '18 at 22:54
  • Since I get `unable to resolve class org.apache.commons.io.FilenameUtils` it's not a valid solution for every environment. –  Jun 07 '18 at 11:04
  • @Kronen the question is about Java, and not 3rd party libraries. –  Oct 24 '18 at 13:51
  • @Erik Aigner Apache commons-io is a Java library, is not a C# or Python library, the question doesn't limit the answers to the standard library at all – Kronen Oct 24 '18 at 14:02
211
String fileName = url.substring( url.lastIndexOf('/')+1, url.length() );

String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
Real Red.
  • 4,991
  • 8
  • 32
  • 44
  • 2
    I upvoted you, because it's slightly more readable than my version. The downvote may be because it doesn't work when there's no extension or no file. – Sietse Mar 03 '09 at 09:59
  • 1
    You can leave off the second parameter to `substring()` – Jon Onstott Dec 06 '14 at 23:47
  • 13
    This doesn’t work for neither `http://example.org/file#anchor`, `http://example.org/file?p=foo&q=bar` nor `http://example.org/file.xml#/p=foo&q=bar` – Matthias Ronge Jan 29 '15 at 08:58
  • 3
    If you let `String url = new URL(original_url).getPath()` and add a special case for filenames that don't contain a `.` then this works fine. – Jason C May 06 '15 at 20:28
  • Downvoted because it won't work if the fragment part contains slashes, and because there are dedicated functions which achieve this in apache commons and in Java since 1.7 – Zoltán May 31 '18 at 11:42
  • 1
    Custom string manipulation on URLs is always a terrible idea. What do you do if a system has different delimiters? Like ``\`` or `:`? –  Jun 07 '18 at 11:00
44

If you don't need to get rid of the file extension, here's a way to do it without resorting to error-prone String manipulation and without using external libraries. Works with Java 1.7+:

import java.net.URI
import java.nio.file.Paths

String url = "http://example.org/file?p=foo&q=bar"
String filename = Paths.get(new URI(url).getPath()).getFileName().toString()
Zoltán
  • 21,321
  • 14
  • 93
  • 134
  • 1
    @Carcigenicate I just tested it again and it seems to work fine. `URI.getPath()` returns a `String`, so I don't see why it wouldn't work – Zoltán Mar 23 '18 at 10:15
  • 1
    Nvm. I realize now that my problem was due to how Clojure handles var-args during Java-interop. The String overload wasn't working because an empty array needed to be passed as well to handle the var-args of Paths/get. It still works though if you get rid of the call to `getPath`, and use the URI overload instead. – Carcigenicate Mar 23 '18 at 13:00
  • @Carcigenicate you mean `Paths.get(new URI(url))`? That doesn't seem to work for me – Zoltán Jan 11 '19 at 09:49
  • getFileName requires android api level 26 – Manuela Mar 12 '20 at 09:11
26

One liner:

new File(uri.getPath).getName

Complete code (in a scala REPL):

import java.io.File
import java.net.URI

val uri = new URI("http://example.org/file.txt?whatever")

new File(uri.getPath).getName
res18: String = file.txt

Note: URI#gePath is already intelligent enough to strip off query parameters and the protocol's scheme. Examples:

new URI("http://example.org/hey/file.txt?whatever").getPath
res20: String = /hey/file.txt

new URI("hdfs:///hey/file.txt").getPath
res21: String = /hey/file.txt

new URI("file:///hey/file.txt").getPath
res22: String = /hey/file.txt
juanmirocks
  • 4,786
  • 5
  • 46
  • 46
26

This should about cut it (i'll leave the error handling to you):

int slashIndex = url.lastIndexOf('/');
int dotIndex = url.lastIndexOf('.', slashIndex);
String filenameWithoutExtension;
if (dotIndex == -1) {
  filenameWithoutExtension = url.substring(slashIndex + 1);
} else {
  filenameWithoutExtension = url.substring(slashIndex + 1, dotIndex);
}
buræquete
  • 14,226
  • 4
  • 44
  • 89
tehvan
  • 10,189
  • 5
  • 27
  • 31
  • 1
    One error handling aspect you need to consider is you will end up with an empty string if you accidentally pass it a url that doesnt have a filename (such as `http://www.example.com/` or `http://www.example.com/folder/`) – rtpHarry Jan 21 '11 at 10:06
  • 2
    The code doesn't work. `lastIndexOf` doesn't work this way. But the intention is clear. – Robert Dec 15 '11 at 01:58
  • Downvoted because it won't work if the fragment part contains slashes, and because there are dedicated functions which achieve this in apache commons and in Java since 1.7 – Zoltán May 31 '18 at 11:42
14
public static String getFileName(URL extUrl) {
        //URL: "http://photosaaaaa.net/photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg"
        String filename = "";
        //PATH: /photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg
        String path = extUrl.getPath();
        //Checks for both forward and/or backslash 
        //NOTE:**While backslashes are not supported in URL's 
        //most browsers will autoreplace them with forward slashes
        //So technically if you're parsing an html page you could run into 
        //a backslash , so i'm accounting for them here;
        String[] pathContents = path.split("[\\\\/]");
        if(pathContents != null){
            int pathContentsLength = pathContents.length;
            System.out.println("Path Contents Length: " + pathContentsLength);
            for (int i = 0; i < pathContents.length; i++) {
                System.out.println("Path " + i + ": " + pathContents[i]);
            }
            //lastPart: s659629384_752969_4472.jpg
            String lastPart = pathContents[pathContentsLength-1];
            String[] lastPartContents = lastPart.split("\\.");
            if(lastPartContents != null && lastPartContents.length > 1){
                int lastPartContentLength = lastPartContents.length;
                System.out.println("Last Part Length: " + lastPartContentLength);
                //filenames can contain . , so we assume everything before
                //the last . is the name, everything after the last . is the 
                //extension
                String name = "";
                for (int i = 0; i < lastPartContentLength; i++) {
                    System.out.println("Last Part " + i + ": "+ lastPartContents[i]);
                    if(i < (lastPartContents.length -1)){
                        name += lastPartContents[i] ;
                        if(i < (lastPartContentLength -2)){
                            name += ".";
                        }
                    }
                }
                String extension = lastPartContents[lastPartContentLength -1];
                filename = name + "." +extension;
                System.out.println("Name: " + name);
                System.out.println("Extension: " + extension);
                System.out.println("Filename: " + filename);
            }
        }
        return filename;
    }
Mike
  • 157
  • 1
  • 2
14

Get File Name with Extension, without Extension, only Extension with just 3 line:

String urlStr = "http://www.example.com/yourpath/foler/test.png";

String fileName = urlStr.substring(urlStr.lastIndexOf('/')+1, urlStr.length());
String fileNameWithoutExtension = fileName.substring(0, fileName.lastIndexOf('.'));
String fileExtension = urlStr.substring(urlStr.lastIndexOf("."));

Log.i("File Name", fileName);
Log.i("File Name Without Extension", fileNameWithoutExtension);
Log.i("File Extension", fileExtension);

Log Result:

File Name(13656): test.png
File Name Without Extension(13656): test
File Extension(13656): .png

Hope it will help you.

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
12

There are some ways:

Java 7 File I/O:

String fileName = Paths.get(strUrl).getFileName().toString();

Apache Commons:

String fileName = FilenameUtils.getName(strUrl);

Using Jersey:

UriBuilder buildURI = UriBuilder.fromUri(strUrl);
URI uri = buildURI.build();
String fileName = Paths.get(uri.getPath()).getFileName();

Substring:

String fileName = strUrl.substring(strUrl.lastIndexOf('/') + 1);
Giang Phan
  • 534
  • 7
  • 15
  • 1
    Unfortunately, your **Java 7 File I/O** solution doesn't work for me. I got an exception. I succeed with this: `Paths.get(new URL(strUrl).getFile()).getFileName().toString();` Thank you for the idea! – Sergey Nemchinov Sep 07 '19 at 14:41
9
String fileName = url.substring(url.lastIndexOf('/') + 1);
Yogesh Rathi
  • 6,331
  • 4
  • 51
  • 81
9

I've come up with this:

String url = "http://www.example.com/some/path/to/a/file.xml";
String file = url.substring(url.lastIndexOf('/')+1, url.lastIndexOf('.'));
Sietse
  • 7,884
  • 12
  • 51
  • 65
8

Keep it simple :

/**
 * This function will take an URL as input and return the file name.
 * <p>Examples :</p>
 * <ul>
 * <li>http://example.com/a/b/c/test.txt -> test.txt</li>
 * <li>http://example.com/ -> an empty string </li>
 * <li>http://example.com/test.txt?param=value -> test.txt</li>
 * <li>http://example.com/test.txt#anchor -> test.txt</li>
 * </ul>
 * 
 * @param url The input URL
 * @return The URL file name
 */
public static String getFileNameFromUrl(URL url) {

    String urlString = url.getFile();

    return urlString.substring(urlString.lastIndexOf('/') + 1).split("\\?")[0].split("#")[0];
}
Tim Autin
  • 6,043
  • 5
  • 46
  • 76
5

Here is the simplest way to do it in Android. I know it will not work in Java but It may help Android application developer.

import android.webkit.URLUtil;

public String getFileNameFromURL(String url) {
    String fileNameWithExtension = null;
    String fileNameWithoutExtension = null;
    if (URLUtil.isValidUrl(url)) {
        fileNameWithExtension = URLUtil.guessFileName(url, null, null);
        if (fileNameWithExtension != null && !fileNameWithExtension.isEmpty()) {
            String[] f = fileNameWithExtension.split(".");
            if (f != null & f.length > 1) {
                fileNameWithoutExtension = f[0];
            }
        }
    }
    return fileNameWithoutExtension;
}
Bharat Dodeja
  • 1,137
  • 16
  • 22
4

Create an URL object from the String. When first you have an URL object there are methods to easily pull out just about any snippet of information you need.

I can strongly recommend the Javaalmanac web site which has tons of examples, but which has since moved. You might find http://exampledepot.8waytrips.com/egs/java.io/File2Uri.html interesting:

// Create a file object
File file = new File("filename");

// Convert the file object to a URL
URL url = null;
try {
    // The file need not exist. It is made into an absolute path
    // by prefixing the current working directory
    url = file.toURL();          // file:/d:/almanac1.4/java.io/filename
} catch (MalformedURLException e) {
}

// Convert the URL to a file object
file = new File(url.getFile());  // d:/almanac1.4/java.io/filename

// Read the file contents using the URL
try {
    // Open an input stream
    InputStream is = url.openStream();

    // Read from is

    is.close();
} catch (IOException e) {
    // Could not open the file
}
Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
2

If you want to get only the filename from a java.net.URL (not including any query parameters), you could use the following function:

public static String getFilenameFromURL(URL url) {
    return new File(url.getPath().toString()).getName();
}

For example, this input URL:

"http://example.com/image.png?version=2&amp;modificationDate=1449846324000"

Would be translated to this output String:

image.png
dokaspar
  • 8,186
  • 14
  • 70
  • 98
2

I've found that some urls when passed directly to FilenameUtils.getName return unwanted results and this needs to be wrapped up to avoid exploits.

For example,

System.out.println(FilenameUtils.getName("http://www.google.com/.."));

returns

..

which I doubt anyone wants to allow.

The following function seems to work fine, and shows some of these test cases, and it returns null when the filename can't be determined.

public static String getFilenameFromUrl(String url)
{
    if (url == null)
        return null;
    
    try
    {
        // Add a protocol if none found
        if (! url.contains("//"))
            url = "http://" + url;

        URL uri = new URL(url);
        String result = FilenameUtils.getName(uri.getPath());

        if (result == null || result.isEmpty())
            return null;

        if (result.contains(".."))
            return null;

        return result;
    }
    catch (MalformedURLException e)
    {
        return null;
    }
}

This is wrapped up with some simple tests cases in the following example:

import java.util.Objects;
import java.net.URL;
import org.apache.commons.io.FilenameUtils;

class Main {

  public static void main(String[] args) {
    validateFilename(null, null);
    validateFilename("", null);
    validateFilename("www.google.com/../me/you?trex=5#sdf", "you");
    validateFilename("www.google.com/../me/you?trex=5 is the num#sdf", "you");
    validateFilename("http://www.google.com/test.png?test", "test.png");
    validateFilename("http://www.google.com", null);
    validateFilename("http://www.google.com#test", null);
    validateFilename("http://www.google.com////", null);
    validateFilename("www.google.com/..", null);
    validateFilename("http://www.google.com/..", null);
    validateFilename("http://www.google.com/test", "test");
    validateFilename("https://www.google.com/../../test.png", "test.png");
    validateFilename("file://www.google.com/test.png", "test.png");
    validateFilename("file://www.google.com/../me/you?trex=5", "you");
    validateFilename("file://www.google.com/../me/you?trex", "you");
  }

  private static void validateFilename(String url, String expectedFilename){
    String actualFilename = getFilenameFromUrl(url);

    System.out.println("");
    System.out.println("url:" + url);
    System.out.println("filename:" + expectedFilename);

    if (! Objects.equals(actualFilename, expectedFilename))
      throw new RuntimeException("Problem, actual=" + actualFilename + " and expected=" + expectedFilename + " are not equal");
  }

  public static String getFilenameFromUrl(String url)
  {
    if (url == null)
      return null;

    try
    {
      // Add a protocol if none found
      if (! url.contains("//"))
        url = "http://" + url;

      URL uri = new URL(url);
      String result = FilenameUtils.getName(uri.getPath());

      if (result == null || result.isEmpty())
        return null;

      if (result.contains(".."))
        return null;

      return result;
    }
    catch (MalformedURLException e)
    {
      return null;
    }
  }
}
Community
  • 1
  • 1
Brad Parks
  • 66,836
  • 64
  • 257
  • 336
1

How about this:

String filenameWithoutExtension = null;
String fullname = new File(
    new URI("http://www.xyz.com/some/deep/path/to/abc.png").getPath()).getName();

int lastIndexOfDot = fullname.lastIndexOf('.');
filenameWithoutExtension = fullname.substring(0, 
    lastIndexOfDot == -1 ? fullname.length() : lastIndexOfDot);
Leon
  • 228
  • 2
  • 8
1

Urls can have parameters in the end, this

 /**
 * Getting file name from url without extension
 * @param url string
 * @return file name
 */
public static String getFileName(String url) {
    String fileName;
    int slashIndex = url.lastIndexOf("/");
    int qIndex = url.lastIndexOf("?");
    if (qIndex > slashIndex) {//if has parameters
        fileName = url.substring(slashIndex + 1, qIndex);
    } else {
        fileName = url.substring(slashIndex + 1);
    }
    if (fileName.contains(".")) {
        fileName = fileName.substring(0, fileName.lastIndexOf("."));
    }

    return fileName;
}
Serhii Bohutskyi
  • 2,261
  • 2
  • 28
  • 28
1

The Url object in urllib allows you to access the path's unescaped filename. Here are some examples:

String raw = "http://www.example.com/some/path/to/a/file.xml";
assertEquals("file.xml", Url.parse(raw).path().filename());

raw = "http://www.example.com/files/r%C3%A9sum%C3%A9.pdf";
assertEquals("résumé.pdf", Url.parse(raw).path().filename());
EricE
  • 74
  • 2
1

If you are using Spring, there is a helper to handle URIs. Here is the solution:

List<String> pathSegments = UriComponentsBuilder.fromUriString(url).build().getPathSegments();
String filename = pathSegments.get(pathSegments.size()-1);
Benjamin Caure
  • 2,090
  • 20
  • 27
  • How the heck this answer waited for almost 3 years to be upvoted? Thanks a lot! This solves also case with path variables. – mate00 May 13 '22 at 08:25
0

In order to return filename without extension and without parameters use the following:

String filenameWithParams = FilenameUtils.getBaseName(urlStr); // may hold params if http://example.com/a?param=yes
return filenameWithParams.split("\\?")[0]; // removing parameters from url if they exist

In order to return filename with extension without params use this:

/** Parses a URL and extracts the filename from it or returns an empty string (if filename is non existent in the url) <br/>
 * This method will work in win/unix formats, will work with mixed case of slashes (forward and backward) <br/>
 * This method will remove parameters after the extension
 *
 * @param urlStr original url string from which we will extract the filename
 * @return filename from the url if it exists, or an empty string in all other cases */
private String getFileNameFromUrl(String urlStr) {
    String baseName = FilenameUtils.getBaseName(urlStr);
    String extension = FilenameUtils.getExtension(urlStr);

    try {
        extension = extension.split("\\?")[0]; // removing parameters from url if they exist
        return baseName.isEmpty() ? "" : baseName + "." + extension;
    } catch (NullPointerException npe) {
        return "";
    }
}
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Chaiavi
  • 769
  • 9
  • 23
0

Beyond the all advanced methods, my simple trick is StringTokenizer:

import java.util.ArrayList;
import java.util.StringTokenizer;

public class URLName {
    public static void main(String args[]){
        String url = "http://www.example.com/some/path/to/a/file.xml";
        StringTokenizer tokens = new StringTokenizer(url, "/");

        ArrayList<String> parts = new ArrayList<>();

        while(tokens.hasMoreTokens()){
            parts.add(tokens.nextToken());
        }
        String file = parts.get(parts.size() -1);
        int dot = file.indexOf(".");
        String fileName = file.substring(0, dot);
        System.out.println(fileName);
    }
}
Blasanka
  • 21,001
  • 12
  • 102
  • 104
0

andy's answer redone using split():

Url u= ...;
String[] pathparts= u.getPath().split("\\/");
String filename= pathparts[pathparts.length-1].split("\\.", 1)[0];
bobince
  • 528,062
  • 107
  • 651
  • 834
0

return new File(Uri.parse(url).getPath()).getName()

0
public String getFileNameWithoutExtension(URL url) {
    String path = url.getPath();

    if (StringUtils.isBlank(path)) {
        return null;
    }
    if (StringUtils.endsWith(path, "/")) {
        //is a directory ..
        return null;
    }

    File file = new File(url.getPath());
    String fileNameWithExt = file.getName();

    int sepPosition = fileNameWithExt.lastIndexOf(".");
    String fileNameWithOutExt = null;
    if (sepPosition >= 0) {
        fileNameWithOutExt = fileNameWithExt.substring(0,sepPosition);
    }else{
        fileNameWithOutExt = fileNameWithExt;
    }

    return fileNameWithOutExt;
}
Campa
  • 11
  • 2
0

String fileNameWithExtension = url.substring( url.lastIndexOf('/')+1);

String fileNameWithoutExtension = fileNameWithExtension.substring(0, fileNameWithExtension.lastIndexOf('.'));

AnilF
  • 108
  • 7
0

All these answers are either too much code or don't address if the url ends in a / or what if it ends in a ///. This is what I used. And I send it into a chooser save dialog so "" just means they have to type in a name.

if(remoteURL!=null) {
  String[] urlParts=remoteURL.split("/");
  String filename=urlParts[urlParts.length-1];
}
-1
create a new file with string image path

    String imagePath;
    File test = new File(imagePath);
    test.getName();
    test.getPath();
    getExtension(test.getName());


    public static String getExtension(String uri) {
            if (uri == null) {
                return null;
            }

            int dot = uri.lastIndexOf(".");
            if (dot >= 0) {
                return uri.substring(dot);
            } else {
                // No extension.
                return "";
            }
        }
Pravin Bhosale
  • 1,920
  • 19
  • 14
-3

import java.io.*;

import java.net.*;

public class ConvertURLToFileName{


   public static void main(String[] args)throws IOException{
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Please enter the URL : ");

   String str = in.readLine();


   try{

     URL url = new URL(str);

     System.out.println("File : "+ url.getFile());
     System.out.println("Converting process Successfully");

   }  
   catch (MalformedURLException me){

      System.out.println("Converting process error");

 }

I hope this will help you.

Ricardo Felgueiras
  • 3,589
  • 6
  • 25
  • 27
  • 2
    getFile() doesn't do what you think. According to the doc it is actually getPath()+getQuery, which is rather pointless. http://java.sun.com/j2se/1.4.2/docs/api/java/net/URL.html#getFile() – bobince Mar 03 '09 at 10:19
-4

I have the same problem, with yours. I solved it by this:

var URL = window.location.pathname; // Gets page name
var page = URL.substring(URL.lastIndexOf('/') + 1); 
console.info(page)