How to reliably get the filename without suffix in javascript?

What is a reliable way to get the filename by removing the suffix in javascript?

I have a let say file:

http://example.com/uploads/images/a51dd42_thumb.jpg and http://example.com/uploads/images/a51dd42_s.jpg

Now I want to get the string http://example.com/uploads/images/a51dd42.jpg

Function

replace () is not what I want as the image file name can have many different types of suffixes

Could regex be the best for this?

If so, what's the reliable code for it?

Thank you in advance

+1


source to share


3 answers


The function replace

is probably what you want, and it can accept a regular expression as a search pattern:

url = url.replace(/_[^\/]+(\.[^\/]*)$/, "$1");

      

What this expression does: Example in Regex101

  • Searches _

    that are not followed by any forward slashes (so we only look at the end segment of the path).

  • Allows any number of characters without the forward slash _

    .

  • Stops match with the last .

    one that finds, followed by zero or more characters (I assume they always have an extension on them); captures .

    characters after it (for example, an extension).

  • Replaces the general match with only .

    and the extension following it. (The $1

    replacement string is special, it means "use the value of the first capture group.)



If your paths may or may not have an extension on them, just add ?

near the end of the regex, before $

: /_[^\/]+(\.[^\/]*)?$/

(which makes everything in the capture group optional).

Example: Live Copy

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Example</title>
  <style>
    body {
      font-family: monospace;
    }
  </style>
</head>
<body>
<script>
  (function() {
    "use strict";

    test("http://example.com/uploads/images/a51dd42_thumb.jpg");
    test("http://example.com/uploads/images/a51dd42_s.jpg");

    function test(url) {
      display("Before: " + url);
      url = url.replace(/_[^\/]+(\.[^\/]*)$/, "$1");
      display("After: " + url);
    }

    function display(msg) {
      var p = document.createElement('p');
      p.innerHTML = String(msg);
      document.body.appendChild(p);
    }
  })();
</script>
</body>
</html>

      

+2


source


You can use:



var s = 'http://example.com/uploads/images/a51dd42_thumb.jpg';
var r = s.replace(/^(.+?)_[^.]+(\.[^\/.]+)$/i, '$1$2');
//=> http://example.com/uploads/images/a51dd42.jpg

      

+1


source


Splitting it up is easy

var start = Filename.split('_')[0], 
file = Filename.split('_')[1],
end = file.split('.')[1];
console.log(start + '.' + end);

      

...

-1


source







All Articles