Get last two params of an URL - javascript

Viewed 955

My URL looks like this

stackoverflow.com/questions/ask/format/return

I need to get only format/return from the above URL. I'm able to assign the complete URL to a variable. Currently i'm doing it on split

url.split("/")[4]
url.split("/")[5]

And this is not Generic. What is the better way to achieve this?

7 Answers

The shortest, cleanest way to do this is by using slice on the splitted URL:

url.split("/").slice(-2).join("/")

Just use the length to help you index from the end:

var res = url.split('/')
var last = res[res.length-1]
var pre_last = res[res.length-2]

A genetic solution,

Var URL = url.split("/"); //

Last = URL[URL.length-1]; // return

LastBefore = URL[URL.length-1]; //format

url = "stackoverflow.com/questions/ask/format/return"

URL = url.split("/"); 
console.log(URL[URL.length-1]) // return 
console.log(URL[URL.length-2]) //format

Look for the last and penultimate values:

let spl = url.split("/");
alert(spl[spl.length-2]+' and '+spl[spl.length-1]);

I'd parse the url to a URL, then use match on the pathname. This way it will also work should you have any searchparams (?foo=bar) in your url

const s = "https://stackoverflow.com/questions/ask/format/return";
const uri = new URL(s);
const m = uri.pathname.match(/([^\/]*)\/([^\/]*)$/);
console.log(m);

Note that you'll get an array holding three entries - 0 being the path combined, 1 the first and 2 the last param.

You can use a simple regex /.*\/(.*\/.*)/) to extract exactly what you want.

str.match(/.*\/(.*\/.*)/).pop()

var str = "stackoverflow.com/questions/ask/format/return",
  res = str.match(/.*\/(.*\/.*)/).pop();
  
console.log(res);

var parts = url.split("/");
lastTwo = [parts.pop(), parts.pop()].reverse().join("/");
Related