如何在javascript中不带后缀的情况下可靠地获取文件名? [英] How to reliably get the filename without the suffix in javascript?

查看:102
本文介绍了如何在javascript中不带后缀的情况下可靠地获取文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过删除javascript中的后缀来获取文件名的可靠方法是什么?

Whats the reliable way on getting the filename of a file by removing suffix in javascript?

我有一个文件,可以说:

I have a file let's say :

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

现在,我想获取字符串 http://example.com/uploads/images/a51dd42 .jpg

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

replace()函数不是我想要的,因为图像文件名可能具有许多不同类型的后缀

replace() function is not what i want since images filename could have many different types of suffixes

也许正则表达式是最好的?

Maybe regex is the best for this?

如果是,那么可靠的代码是什么?

If yes, whats the reliable code for it?

预先感谢

推荐答案

replace函数可能是您想要的 ,它可以接受正则表达式作为搜索模式:

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

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

该表达式的作用: Regex101上的示例

  • 查找没有任何斜杠的_(因此,我们仅查看路径中的最后一段).

  • Looks for an _ that isn't followed by any slashes (so we're only looking at the final segment in the path).

允许在_之后的任意数量的非斜杠字符.

Allows any number of non-slash characters after the _.

与找到的最后一个.中的字符匹配的停止符,后跟零个或多个字符(我假设这些字符始终具有扩展名);捕获.及其后的字符(例如扩展名).

Stops matching those at the last . it finds followed by zero or more characters (I'm assuming these always have an extension on them); captures the . and the characters after it (e.g., the extension).

仅用.和其后的扩展名替换整体匹配项. (替换字符串中的$1是特殊的,它的意思是使用第一个捕获组的值.)

Replaces the overall match with just the . and extension following it. (The $1 in the replace 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 a ? near the end of the regex, just before the $: /_[^\/]+(\.[^\/]*)?$/ (that makes everything in the capture group optional).

示例:实时复制

<!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>

这篇关于如何在javascript中不带后缀的情况下可靠地获取文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆