amenoire
amenoire

Reputation: 1892

JS method to break RESTful URL into parts and return them

I have an AngularJS web application. Application has similar functionality as Dev HTTP Client (it sends different HTTP methods to REST resources on the project). It looks like this:

enter image description here

Now I would like to have a possibility to determine something about the entered url. Basicaly, url can be off 3 types:

  1. http://localhost:8080/REST/api/contents/ - resources collection
  2. http://localhost:8080/REST/api/contents/Q1W2E3R4T5 - single resource
  3. http://localhost:8080/REST/api/contents/Q1W2E3R4T5/questions - child resource collection

What I want is to have a function that takes url as a parameter and returns an object with 3 properties:

Does anyone know how to do such thing using JS or AngularJS?

Every useful answer is highly appreciated and evaluated. Thank you.

Upvotes: 0

Views: 184

Answers (1)

Johan
Johan

Reputation: 35213

Something like this perhaps?

function breakUrl(url){

    var start = 'http://localhost:8080/REST/api/',
        s1 = url.split(start),
        s2 = s1[1].split('/');

    return {  
        resource: s2[0] || '',
        single: s2[1] || '',
        child: s2[2] || ''
    };

}

console.log(breakUrl('http://localhost:8080/REST/api/contents'));
console.log(
       breakUrl('http://localhost:8080/REST/api/contents/Q1W2E3R4T5/questions'));

http://jsfiddle.net/BL3JL/

Upvotes: 1

Related Questions