正在尝试编写一个javascript bookmarklet,以便从前端链接跳转到CMS编辑页面链接。
所以取一个像这样的url
http://www.example.com/events/13097/article
并创建一个像这样的url
http://www.example.com/admin/edit.php?class=events&id=13097
我想我需要使用正则表达式来获取类和id,然后将其封装到一个javascript函数中--但我是一个绝对的初学者,不知道是否有人能帮我入门?
发布于 2012-04-04 22:26:02
你不需要正则表达式,试试这个:
var url = ""+window.location;
var urlparts = url.split('/');
window.location = "http://www.example.com/admin/edit.php?class="+urlparts[3]+"&id="+urlparts[4];从URL中拆分类和id,并在重定向中重复它们。第一行将window.location转换为一个字符串,您也可以使用String(window.location)来执行此操作,但这更加冗长。
要获取域名,您可以使用:
"http://"+urlparts[2]+"/admin/edit.php?class="+urlparts[3]+"&id="+urlparts[4]EDIT:实际上,你可以使用window.location.href.split('/')获取urlparts,或者在window.location object中模拟其他感兴趣的项目的原始代码(示例来自this帖子)。
hash: "#10013173"
host: "stackoverflow.com"
hostname: "stackoverflow.com"
href: "https://stackoverflow.com/questions/10012966/change-url-with-bookmarklet/10013173#10013173"
origin: "http://stackoverflow.com"
pathname: "/questions/10012966/change-url-with-bookmarklet/10013173"
port: ""
protocol: "http:"
search: ""发布于 2012-04-04 22:21:46
下面是在C#单元测试中使用的正则表达式的示例。因为您不熟悉正则表达式,所以模式与源url相同,只是有两个capture groups:一个用于类(?<class>[^/]+),另一个用于id (?<id>[^/]+)。每种方法的工作原理是,它接受一个或多个不是斜杠(^/)的字符(加号),并将其存储在尖括号中名称的正则表达式组中。
var source = "http://www.domain.com/events/13097/article";
var expected = "http://www.domain.com/admin/edit.php?class=events&id=13097";
var pattern = "http://www.domain.com/(?<class>[^/]+)/(?<id>[^/]+)/article";
var r = new Regex(pattern);
var actual = r.Replace(source, "http://www.domain.com/admin/edit.php?class=${class}&id=${id}");
Assert.AreEqual(expected, actual);发布于 2012-04-04 22:22:36
//var str = window.location.href;
var str = "http://www.example.com/events/13097/article";
var re = /events\/(\d+)\//;
var match = str.match(re);
var newURL = "http://www.example.com/admin/edit.php?class=events&id=" + match[1];
alert(newURL);https://stackoverflow.com/questions/10012966
复制相似问题