在 Javascript 的 URL 中查找基本名称

Find base name in URL in Javascript

提问人:Pekka 提问时间:1/2/2010 最后编辑:Pekka 更新时间:1/9/2016 访问量:16499

问:

我想从 Javascript 中的图像 URL 中提取基本名称。有人愿意在正则表达式上帮我一把吗?

规则是:

  • 返回最后一个左边的所有内容/.

    www.domain.com/images/ image.hires.jpg

  • 如果未找到,则返回完整的基名称 www.domain.com/images/ image_hi_res.

我有一个笨拙的,但不知道如何使和可选以及如何寻找最后一个。/\/[^.]+\.[^.]+$//..

一如既往地为大家的宝贵投入而欢呼。我选择了开箱即用的正则表达式。

JavaScript 正则表达式

评论

1赞 whunmr 1/2/2010
pagecolumn.com/tool/regtest.htm

答:

1赞 Gumbo 1/2/2010 #1

试试这个正则表达式:

/([^/]+(?=\.[^/.]*$)|[^/.]+$)/
1赞 Tim Pietzcker 1/2/2010 #2

在您的示例中,假设输入字符串是整个 URL,仅此而已,我已经成功了

/\/[^\/]+(?=\.[^.]+$)|\/[^\/]+$/

这首先尝试匹配从最后一个到最后一个的所有内容;如果没有点,它将尝试匹配从字符串的最后一个到末尾的所有内容。/./

前导包含在匹配中(JavaScript 不支持后视,否则我可以使用它),因此您需要砍掉匹配的第一个字符。/

12赞 Mirko N. 1/2/2010 #3

在这种情况下,我实际上不会使用正则表达式,而只是使用 和 .类似的东西lastIndexOfsubstring

function findBaseName(url) {
    var fileName = url.substring(url.lastIndexOf('/') + 1);
    var dot = fileName.lastIndexOf('.');
    return dot == -1 ? fileName : fileName.substring(0, dot);
}

评论

0赞 Lucas Serafim 9/26/2015
如果你想要当前的 url,只需使用上面的函数,如下所示: findBaseName(window.location.href);
30赞 Christoph 1/2/2010 #4

另一种解决方案:

url.replace(/^.*\/|\.[^.]*$/g, '')

评论

0赞 Patartics Milán 9/24/2015
@themis仅适用于新顶级域名
-2赞 WRFan 1/28/2010 #5

我建议使用 FileSystemObject activex。当然,您需要在注册表中将其标记为安全才能在没有唠叨屏幕的情况下执行它,但它非常有用。您的电话...GetBaseName 函数执行您想要的操作。

评论

0赞 cobbal 1/28/2010
这消除了跨平台和跨浏览器的兼容性,而收益相对较小。
0赞 Christophe Marois 1/9/2016 #6

当您有权访问 DOM 时,可以使用标记的本机属性:HTMLHyperlinkElementUtils<a>

function urlInfo (url) {

  var props = 'hash host hostname href origin password pathname port protocol username search';

  if (!window.urlInfoAnchorElement)
    window.urlInfoAnchorElement = document.createElement('a');

  urlInfoAnchorElement.href = url;

  return props.split(' ').reduce(function (m, v, i) {
    m[v] = urlInfoAnchorElement[v]; return m;
  }, {});

}

// Example:
urlInfo('http://localhost:4000/guidelines/7yQxvndK?get=sup&love=1#oiwjef');

/* => {
  hash: "#oiwjef"
  host: "localhost:4000"
  hostname: "localhost"
  href: "http://localhost:4000/guidelines/7yQxvndK?get=sup&love=1#oiwjef"
  origin: "http://localhost:4000"
  password: ""
  pathname: "/guidelines/7yQxvndK"
  port: "4000"
  protocol: "http:"
  search: "?get=sup&love=1"
} */