Last Updated: February 25, 2016
·
1.203K
· nickjacob

give your window.location a "file"

Sometimes its nice to know just the filename that was requested, but window.location only gives you a pathname, which is the relative path (based on/from window.location.origin). So here's a little regex oneline IIFE (self-invoking/executing function):

(function(window,undefined){
    if(!window || window.location) return;
    // one-line version (bc everything good is 1 line, right???)

    window.location.file = (/\/\w*\.[a-zA-Z {0,10}$/.exec(window.location.pathname)[0] || '').replace('/','');

    // split into multiple lines for this tiny box:

    var pattern =/\/\w*\.[a-zA-Z]{0,10}/,
    file = pattern.exec(window.location.pathname)[0];
    file = (file || '').replace('/','');
    window.location.file = file;
)(window);

Note that this is checking for files with an extension that is 0-10 characters