Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to split URL into array in clean way?

I need to extract the directory and file name in a different input of user URL's.

Some examples would include:

  • https://foo/s3.amazonaws.com/TOP_PROD_IMAGE/WS-25612-BK_IMRO_1.jpg
  • http://192.168.12.44:8090/TOP_PROD_IMAGE/R3CRDT-HZWT_IMRO_1.jpg
  • www.foobar-images.s3.amazonaws.com/TOP_PROD_IMAGE/WS-25612-BK_IMRO_1.jpg

What I really need is the TOP_PROD_IMAGE and WS-25612-BK_IMRO_1.jpg file name.

So I would need to account for users who enter http:// or https:// or just www. so I tried using string.split('/') but that obviously wouldn't work in all cases. Is there something that could give me an array despite the double // in cases where user enters http? Thanks!

like image 549
rec0nstr Avatar asked Dec 31 '22 09:12

rec0nstr


1 Answers

Consider:

const [file, folder] = url.split('/').reverse();

With this you wouldn't need to consider http:// or any //

like image 70
C_Ogoo Avatar answered Jan 02 '23 22:01

C_Ogoo