Keep only the first directory / page after the address
I know this has been discussed a billion times, but I have a specific question on how to move the first page / folder from a url to Javascript.
Let's say I go to my site like this: http://www.user.com/grabMe/dontGrabme
I only want to grab "grabMe", but please note: "grabMe" can change to something different every time. Although, this is definitely a sample. I want to take the first "folder" after my domain and not accept anything else after that.
Thanks in advance.
Split the url by /
and take the third element.
var str = 'http://www.user.com/grabMe/dontGrabme'.split('/')[3];
DEMO
You can use the property pathname
of the location object:
location.pathname.split('/')[1]
If the current url of the page http://www.user.com/grabMe/dontGrabme
, then pathname
will /grabMe/dontGrabme
and will split it by /
to give you an array from which you grab the second element.
var myString = document.URL;
myRegexp = /^.*\/\/.*\/(.*)\/.*$/;
var match = myRegexp.exec(myString);
console.log(match[1]);