试图通过正则表达式返回部分网址(jquery)

时间:2009-06-06 01:51:13

标签: jquery

我正在尝试将网址的一部分作为字符串返回并将其添加到其他位置。

所以我这样做:

var somestring = $("#hello").attr("href").text().replace(/part\/(\d+)/g, "part-$1");

只有我不认为这是正确的。将“part- $ 1”作为字符串返回的正确方法是什么?

谢谢!

以下是示例:

http://jsbin.com/agiyu/edit

如果成功,输出应该像Fake Urlpart-333。

谢谢!

2 个答案:

答案 0 :(得分:0)

尝试:

var somestring = $("#hello").attr("href").replace(/^.*\/part\/(\d+).*$/g, "part-$1");
$("#hello").append(somestring);
  • 您无需致电text(),因为attr()会返回一个字符串。
  • 你忘记了一个结束引号。
  • 由于$("#hello")返回单个元素,因此无需each()

答案 1 :(得分:0)

这是一个提示:

document.write(document.location.protocol);
document.write(document.location.host);
document.write(document.location.pathname);