【问题标题】:jquery regex trim beginning and end of a url stringjquery regex修剪url字符串的开头和结尾
【发布时间】:2012-06-06 22:27:43
【问题描述】:

我的链接带有如下所示的 href 属性:

http://company.com/inetucm/groups/public/@enterprise/documents/pagecontent/s_014654.html

我想编写一个 jquery 函数,将 s_014654 设置为一个变量,稍后我将使用它来创建不同的 url 结构。

谁能帮我解决一下这个语法。

【问题讨论】:

  • “一个 jQuery 函数”是什么意思?您是在谈论创建插件吗?如果您只想要一个可重用的函数,只需将目前的任何一个答案封装在一个标准函数中......
  • 我们这里有一个辩论,你能告诉我们这两种方式哪个更容易理解吗?
  • 你还在烦恼吗?如果不是,您应该接受其中一个答案。 (Writing "Accept" seems to be broken though)

标签: javascript jquery regex


【解决方案1】:
var url = ....;
var arr = url.split('/');
var value = arr.pop().match(/^(.+)\.html$/)[1];
alert(value); // "s_014654"

Live DEMO


更新:(基于评论)

<a href="http://company.com/inetucm/groups/public/@enterprise/documents/pagecontent/s_014654.html" />
<a href="http://company.com/inetucm/groups/public/@enterprise/documents/pagecontent/AAAAAAAA.html" />
<a href="http://company.com/inetucm/groups/public/@enterprise/documents/pagecontent/BBB.html" />    
<a href="http://company.com/inetucm/groups/public/@enterprise/documents/pagecontent/fdskl489j.html" />

jQuery:

var arr = $('a').map(function(){ 
    return this.href.split('/').pop().match(/^(.+)\.html$/)[1]; 
}).get();

这将返回一个数组中的所有值。

Live DEMO

【讨论】:

  • 你也可以arr.pop().match(:-P
  • @zerkms。是的,它更容易阅读和理解,但也可以使用正则表达式来完成......
  • @gdoron: 你确定用[^/]+ 替换.+ 变化很大---stackoverflow.com/a/10923281/251311 吗?同时 - 我们需要考虑split + pop
  • @zerkms。我问了OP;这是一个有趣的问题,甚至比 OP 问题... :)
  • @zerkms。你应该read this。是的,这是题外话,但该死的很有趣!
【解决方案2】:

类似这样的:

var url = "http://company.com/inetucm/groups/public/@enterprise/documents/pagecontent/s_014654.html";

var value = url.match(/([^/]+)\.html$/)[1];

感谢 gdoron 用我自己的正则表达式更新的小提琴:http://jsfiddle.net/Fjp8E/2/

模式([^/]+)\.html$ 查找一个或多个非斜线字符,该字符后跟在字符串末尾的“.html”。

【讨论】:

  • 值得一提的是,regex 抓取每个没有斜线.html 结尾的字符。 +1。
  • 你应该read this,那家伙真有趣!对不起,我不得不和别人分享...
猜你喜欢
  • 2011-03-01
  • 2021-05-12
  • 2013-08-18
  • 2011-02-06
  • 2021-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多