如何使用javascript从此URL中提取数据?

时间:2012-03-13 23:28:40

标签: javascript jquery

我需要使用javascript / jQuery从这个url中包含的数据构建一个字符串:

http://www.example.com/members/admin/projects/?projectid=41

返回的字符串应如下所示:

/ajax/projects.php?projectid=41

显然,如果不存在查询字符串,该方法仍应返回相同格式的字符串减去查询字符串。 e.g。

http://www.example.com/members/admin/messages/

应该返回......

/ajax/messages.php

我做了很多尝试,由于我对正则表达式的把握很差,所有人都没有成功,并且感觉好像我对这个主题的影响越多,我就越困惑自己。

如果有人可以提供帮助,我们将不胜感激。

编辑:网址的“管理员”部分是用户的“用户名”,可以是任何内容。

3 个答案:

答案 0 :(得分:1)

我确切地知道你要做什么。为了做到这一点你只需将你的字符串分成问号,然后使用你的数组的最后一项。

var data = your_url.split('?');
var  newUrl = '/ajax/projects.php' + (data.length > 1 ? data[length-1] : "");

你会得到你的网址。

但你可以做的是使用你的脚本执行相同的url只需添加一个参数IsAjax = true然后在代码隐藏中检查它并执行你的ajax逻辑。

e.g。

$('#somelink').onclick(function(){
   $.ajax({ url: $(this).href, data { IsAjax: true } .... }
});

使用这种方式,您将拥有更强大的应用程序。

答案 1 :(得分:1)

这是一个功能,它将根据您在上面列出的规则获取您的网址并返回一个新网址:

function processURL(url) {
    var base = "", query = "";
    var matches = url.match(/([^\/\?]+)(\/$|$|\?|\/\?)/);
    if (matches) {
        base = matches[1];
        matches = url.match(/\?[^\?]+$/);
        if (matches) {
            query = matches[0];
        }
    }
    return("/ajax/" + base + ".php" + query);
}

并且,一个测试应用程序,显示它处理一堆URL:http://jsfiddle.net/jfriend00/UbDfn/

Input URLs:

var urls = [
    "http://www.example.com/members/admin/projects/?projectid=41",
    "http://www.example.com/members/bob/messages/",
    "http://www.example.com/members/jill/projects/",
    "http://www.example.com/members/alice/projects?testid=99",
    "http://www.example.com/members/admin/projects/?testid=99"
];

Output results:

/ajax/projects.php?projectid=41
/ajax/messages.php
/ajax/projects.php
/ajax/projects.php?testid=99
/ajax/projects.php?testid=99

为了解释,第一个正则表达式查找:

a slash
followed by one or more characters that is not a slash and not a question mark
followed by one of the four sequences
    /$    a slash at the end of the string
    $     end of the string
    ?     a question mark
    /?    a slash followed by a question mark

这个正则表达式的要点是获取字符串结尾或查询参数之前的路径的最后一段,并且它是否容忍最后一个尾部斜杠是否存在以及是否有任何查询参数

答案 2 :(得分:0)

var str = "http://www.example.com/members/admin/projects/?projectid=41";
var newStr = "/ajax/" + str.split("/").slice(-2).join(".php");
console.log(newStr);