【问题标题】:(Javascript) How to extract the last part of the current URL - without the file extension?(Javascript)如何提取当前 URL 的最后一部分 - 没有文件扩展名?
【发布时间】:2012-06-06 00:00:13
【问题描述】:

我目前正在使用以下 javascript 代码:

<script type="text/javascript"> 
    urlPath=window.location.pathname; 
    urlPathArray = urlPath.split('/'); 
    urlPath1=urlPathArray[2]; 
    document.write('<a href="http://www.example.com/contact.php?id='+urlPath1+'">test</a>'); 
    </script> 

假设当前 URL 是 http://www.example.com/products/0033.htm

javascript 生成一个指向http://www.example.com/contact.php?id=0033.htm 的超链接

如何修改此脚本,使 urlPath1 和最终的超链接没有“.htm”部分?

【问题讨论】:

  • 文件扩展名是任意大小还是只有.htm?因为你可以只使用一个子字符串
  • urlPathArray[2]; 使用urlPathArray[urlPathArray.length - 1] 获取最后一个元素...

标签: javascript url location extract


【解决方案1】:

完全按照您为获取文件名所做的操作,但在 . 而不是 / 上拆分并获取第一部分。

【讨论】:

  • 它可能不起作用,因为第一部分将是/products/0033而不是0033。location.pathname返回相对路径。
【解决方案2】:
var urlPath = window.location.pathname,
    urlPathArray = urlPath.split('.'),
    urlPath1 = urlPathArray[0].split('/').pop(); 

document.write('<a href="http://www.example.com/contact.php?id='+urlPath1+'">test</a>'); 

【讨论】:

  • 点可以在路径名的中间。您需要隔离路径的最后一段,然后删除可能存在的任何扩展。
  • 您好,格蕾丝,感谢您的快速回复。我尝试了您的示例,但它似乎不起作用。有什么想法吗?
  • 更新:我使用以下修改后的代码解决了它:urlPath=window.location.pathname; urlPathArray = urlPath.split('/'); urlPath1=urlPathArray[urlPathArray.length - 1]; urlPath2= urlPath1.split('.'); productID=urlPath2[0]; document.write('&lt;a href="http://www.example.com/contact.php?id='+productID+'"&gt;test&lt;/a&gt;'); 再次感谢您的帮助:)
  • 很高兴您自己修复了它! :)
  • 如果您回答自己的问题,则应将其作为答案并选择“正确”,这是 Stack Overflow 鼓励的,因为它有助于将其他人引导至答案stackoverflow.com/help/self-answer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-10
  • 2013-11-16
  • 1970-01-01
  • 1970-01-01
  • 2011-10-23
  • 2013-09-17
  • 1970-01-01
相关资源
最近更新 更多