Sajak Upadhyaya
Sajak Upadhyaya

Reputation: 401

Parse url string object into host name in AngularJS

I have a scope variable that returns me an absolute url stored by the user. While displaying I would like to only show the host name for the given object.

for example. $scope.url ="www.myurl.com/zyas?nxs"

i want to only display it as www.myurl.com.

How can I achieve this?

Upvotes: 0

Views: 1503

Answers (5)

Ram_T
Ram_T

Reputation: 8484

In a better way, you can do this without splitting and doing things

  var url = new URL("http://www.myurl.com/zyas?dsfadf");
  console.log(url.host); // gives the host name www.myurl.com

Upvotes: 0

Sajak Upadhyaya
Sajak Upadhyaya

Reputation: 401

I went with the normal split provided by JavaScript. Here's how I parsed it to the hostname and pushed it back to my JSON object.

    $scope.blogposts = result.data
                // console.log(urls);
                $scope.blogposts.forEach(function(blog){
                    console.log(blog);
                var a = blog.url.split('/')
                // blog.push({'viewUrl':'a[0]'})
                blog["viewUrl"] =a[0]
            })

Upvotes: 0

var hostName = $scope.url.split('/')[0];

Upvotes: 1

Sai
Sai

Reputation: 2658

You can do like this:

$scope.url ="www.myurl.com/zyas?nxs"

$scope.host = $scope.url.split('/')[0];

Upvotes: 1

Aravind
Aravind

Reputation: 41573

Have a look at the below code

string s = "www.myurl.com/zyas?nxs";
string newstr = s.split("/"); //newstr == "www.myurl.com"

Upvotes: 1

Related Questions