user995317
user995317

Reputation: 355

How to parse string/URL with jQuery

I have ajax call and from json i get URL like this:

http://pp.somedomain.com/pp/url/245/http%253A%252F%252Fmydomain.com%252Fblog%252F25-03-11%252Fawesome-story-bro%252F%253Fstuff%253D492039402

Now I would like to parse that I would only get my domain.com path from that. So the end result would be:

http://mydomain.com/blog/25-03-11/awesome-story-bro/

But I have no clue how to do that with Javascript/jQuery. Anyone could help me out? I read tutorial and somehow I have to count / and then cut it somehow.

Upvotes: 0

Views: 155

Answers (3)

Sahil Mittal
Sahil Mittal

Reputation: 20753

To parse the url from the string-

Using exec

 var result = /[^/]*$/.exec(a)[0];

Using lastIndexOf and substring:

var n = a.lastIndexOf('/');
var result = a.substring(n + 1);

Then you can decode the url using decodeURIComponent-

var my_url = decodeURIComponent(result);


View Demo


(but it seems that the string is erroneous as explained by @hjpotter92. pl check)

Upvotes: 0

hjpotter92
hjpotter92

Reputation: 80639

Your html part has been encoded twice. You'd first need to use the html-unescape call and then later use the decodeURIcomponent.

Also, note that your URL in still incorrect since you've the following in it:

%252F%mydomain

Notice the %mydomain part? It should be:

%252F%252Fmydomain

and then you can use the following function calls:

x = "http%253A%252F%252Fmydomain.com%252Fblog%252F25-03-11%252Fawesome-story-bro%252F%253Fstuff%253D492039402"
y = unescape(x) // y = "http%3A%2F%2Fmydomain.com%2Fblog%2F25-03-11%2Fawesome-story-bro%2F%3Fstuff%3D492039402"
z = decodeURIComponent(y) // z = "http://mydomain.com/blog/25-03-11/awesome-story-bro/?stuff=492039402"

Upvotes: 2

aedips
aedips

Reputation: 49

I think your url isnot valid. When I try decode with decodeURIComponent(), it throws URI malformed exception

decodeURIComponent("http%253A%252F%mydomain.com%252Fblog%252F25-03-11%252Fawesome-story-bro%252F%253Fstuff%253D492039402")

Upvotes: 2

Related Questions