0

I need to build a string from the data contained in this url using javascript/jQuery:

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

The string returned should look as follows:

/ajax/projects.php?projectid=41

Obviously if there is no query string present, the method should still return a string of the same format minus the query string. e.g.

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

should return...

/ajax/messages.php

I've made numerous attempts, all met without success due to my poor grasp of regular expressions, and it feels as though the ore I rad on the subject the more I am confusing myself.

If someone could help it would be greatly appreciated.

EDIT: The 'admin' portion of the url is a users 'username' and could be anything.

4
  • If I'm not mistaken, you can use $.ajax get api.jquery.com/jQuery.get and then send it out to your members.php page Commented Mar 13, 2012 at 23:32
  • @gdoron Sorry that was a mistype and should have read messages.php. Commented Mar 13, 2012 at 23:33
  • hard to follow what the rules are Commented Mar 13, 2012 at 23:33
  • @andrewliu Indeed I can, however I need to dynamically build the url string I send via jQuerys $.ajax or $.get methods from the actual href stored in the DOM. The /ajax/messages.php versions of my pages are split down versions containing just the replacement elements which are sent back via json. Commented Mar 13, 2012 at 23:36

4 Answers 4

1

Here's a function that will take your URL and return a new one according to the rules you've listed above:

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);
}

And, a test app that shows it working on a bunch of URLs: 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

To explain, the first regular expression looks for:

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

The point of this regex is to get the last segment of the path that comes before either the end of the string or the query parameters and it's tolerant of whether the last trailing slash is there or not and whether there are any query parameters.

Sign up to request clarification or add additional context in comments.

6 Comments

This looks almost perfect jfriend00... Thank you. However I failed to mention that the username can change, the examples I used had 'admin' as the username but it could be anything. My apologies for not being clearer.
OK, I will work on a revision that can handle that. Hang on a few minutes.
@gordyr - Code and test cases updated to work with any username.
I've just seen the update to your question. And I think regardless of the fact that ecapsarello's solution also works for the rules I gave, your answer deserves to be the one marked for its completeness, jsFiddle and excellent explanation as well as the fact that it will work for other valid url's. A genuinely excellent answer, thank you.
@gordyr - it depends upon whether you want the URL to require the trailing slash or not. The epascarello split algorithm requires it, this algorithm does not. Try and run the epascarello function on the test URLs I presented in my answer.
|
1

I know exactly what you are trying to do. In order to do it your way just split your string on question mark and then use last item form your array.

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

and you will have your url.

But what you can do is execute same url using your Script just add one parameter IsAjax=true and then check it in codebehind and execute your ajax logic.

e.g.

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

Using this way you will have more robust app.

2 Comments

Thanks Senad your second example is exactly what I would normally do. However I cannot do so in this case. I won't go into the reason why here, but needless to say I need to achieve this purely clientside. With regards to your first suggestion. Wouldn't splitting at the question mark fail to work in URL's that don't contain query strings? Thanks for the suggestions though.
Yes, I have updated script so it will work without query string, it will call your url but there won't be any error.
0

I'll assume that by

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

should return...

/ajax/members.php

you meant - should return...

/ajax/messages.php

If that is the case try

var query = url.split('?');
var paths = query[0].split('/');
var path = paths.pop();

if (path == '')  //when there is trailing slash
    path = paths.pop();

if (query.length == 1) //no query string
    newurl = '/ajax/' + path + '.php';
else //query string
    newurl = '/ajax/' + path + '.php?' + query[1];

I'm sure it can be made simpler and better, but that might give you a start.

Comments

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

2 Comments

Many thanks it works great! However, before I mark this as answered, jfriend00's solution works also but is using a regexp. I'm now trying to work out which solution is the best method to use.
This algorithm relies on a trailing slash before the ? and would not work with a URL like this: http://www.example.com/members/admin/projects?projectid=41 which is probably also a valid URL to reach that page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.