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.

+3


source to share


3 answers


Split the url by /

and take the third element.

var str = 'http://www.user.com/grabMe/dontGrabme'.split('/')[3];

      



DEMO

+3


source


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.

+1


source


var myString = document.URL;
myRegexp = /^.*\/\/.*\/(.*)\/.*$/;
var match = myRegexp.exec(myString);
console.log(match[1]);

      

+1


source







All Articles