3

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?

Matarishvan
  • 2,382
  • 3
  • 38
  • 68

7 Answers7

3

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

url.split("/").slice(-2).join("/")
NonameSL
  • 1,405
  • 14
  • 27
2

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]
kabanus
  • 24,623
  • 6
  • 41
  • 74
1

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
0

Look for the last and penultimate values:

let spl = url.split("/");
alert(spl[spl.length-2]+' and '+spl[spl.length-1]);
Mitya
  • 33,629
  • 9
  • 60
  • 107
0

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.

baao
  • 71,625
  • 17
  • 143
  • 203
0

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);
Koushik Chatterjee
  • 4,106
  • 3
  • 18
  • 32
-1
var parts = url.split("/");
lastTwo = [parts.pop(), parts.pop()].reverse().join("/");
blue112
  • 52,634
  • 3
  • 45
  • 54