Last Updated: February 25, 2016
·
1.444K
· 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

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside