everyone. Sometimes I need some way to get some part of external site url in my angular code. But there's obviously no way to do it with native angular services, and I don't wanna use some Jquery library for parsing url. I need some service for url parsing which. Where can I find such service? Thx!
Asked
Active
Viewed 4,386 times
3 Answers
13
You can do it in Vanilla JavaScript.
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.search; // => "?search=test"
parser.hash; // => "#hash"
parser.host; // => "example.com:3000"

Simone
- 20,302
- 14
- 79
- 103
-
Can I get any GET parameter by this way? – Eriendel Feb 02 '14 at 22:20
-
Of course you can. In my example you'd parse `parse.search`. Also see: [How to get the value from URL Parameter?](https://stackoverflow.com/questions/979975/how-to-get-the-value-from-url-parameter) – Simone Feb 02 '14 at 22:22
-
OMG! Do you really have to create a virtual `` element to parse a link? – mrded Aug 12 '16 at 15:11
-
You could also reuse an existing one, assuming the `href` attribute contains the same URL you want to parse. – Simone Jul 28 '17 at 11:34
0
I guess you could use the $sce service:
function($scope, $sce) {
$scope.getHtml = function() {
return $sce.trustAsResourceUrl(myUrlHere);
};
}
As mentioned in other post, provided that this is not subject to CORS.

Edwin Dalorzo
- 76,803
- 25
- 144
- 205
-4
By Parsing, I'm assuming you mean fetching of content/data from a url.
Proving the url allows any domain ( 'Access-Control-Allow-Origin', '*' ) or your domain, Angular does have ajax functions built in, simular to jquery et all.
http://docs.angularjs.org/api/ng.$http
Copied direct from the anguar doc
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Rob Sedgwick
- 5,216
- 4
- 20
- 36
-
1No, actually, by parsing I meant getting some parts of url string for example get parameters. – Eriendel Feb 02 '14 at 22:18
-
oh ok : ) regular js will do then, Angular would not have any need to recreate that. - use of externalurlstring.split("/") and such - I thought Simone's answer is pretty cool – Rob Sedgwick Feb 02 '14 at 22:54