0

I want to remove everything in the URL and only keep the name of the file/image. The URL is a dynamic input/variable.

Code:

var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
str = str.replace("http://website.com/sudir/sudir/subdir/", "")
         .replace(/[^a-z\s]/gi, ' ').replace("_", " ")
         .replace("subdir", "").toLowerCase().slice(0,-4);

5 Answers5

1

This function will give you the file name,

function GetFilename(url)
{
   if (url)
   {
      var m = url.toString().match(/.*\/(.+?)\./);
      if (m && m.length > 1)
      {
         return m[1];
      }
   }
   return "";
}
Chamika Sandamal
  • 23,565
  • 5
  • 63
  • 86
1

You can do this easily with lastIndexOf():

var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
str.substring(str.lastIndexOf("/") + 1)
//"Image_01.jpg"
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
0

From How to catch the end filename only from a path with javascript?

var filename = path.replace(/.*\//, '');

From Getting just the filename from a path with Javascript

var fileNameIndex = yourstring.lastIndexOf("/") + 1;
var filename = yourstring.substr(fileNameIndex);
Community
  • 1
  • 1
0

I know you haven't specified the exact URL format and whether this may be possible in your situation, but this may be a solution worth considering.

Javascript

var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg?x=y#abc";
console.log(str.split(/[?#]/)[0].split("/").slice(-1)[0]);

str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
console.log(str.split(/[?#]/)[0].split("/").slice(-1)[0]);

On jsfiddle

Xotic750
  • 22,914
  • 8
  • 57
  • 79
0

You can always Regex to extract data from strings: The Regex to extract data from URL:

"http://website.com/sudir/sudir/subdir/(?<FileName>[0-9A-Za-z._]+)"
Dawood Awan
  • 7,051
  • 10
  • 56
  • 119