0

Say I have a route that is http://www.stackoverflow.com/questions/ask

Is there a way I can read through that link and check the see if the word "ask" is there?

So,

If(link.contains["ask"]) {
     containsAsk = true;
}

To be clear, I am trying to pull the link from the browser, and do not have it defined within my code.

Daniel
  • 3,541
  • 3
  • 33
  • 46
CodyCS
  • 59
  • 1
  • 2
  • 11
  • Possible duplicate of [How to check whether a string contains a substring in JavaScript?](https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript) – Christopher Moore Jun 19 '17 at 13:54
  • I want to get the link from the browser, not a string I've defined in the code – CodyCS Jun 19 '17 at 13:55
  • you could querie the router to get the current route which will return a string, then check it for a sub string. – Nicholas Tsaoucis Jun 19 '17 at 13:57
  • Ok - what have you already tried? What version of angular are you using? Please add some more information to your question to help get a good answer – Christopher Moore Jun 19 '17 at 13:57
  • Could you specify what angular is this question related to? angular2/4 or angularjs? to apply the correct tags – Jota.Toledo Jun 19 '17 at 14:04

1 Answers1

4

In angular2/4 you could inject into a component an instance of ActivatedRoute, transform it to string with toString() and check the value of it. For example

@Component()
export class TestComponent{
   constructor(private _route: ActivatedRoute){
     let link = _route.toString();
     console.log(link.contains('ask'));
   }
}

Note that this method will return a string with the form Route(url:'${url}', path:'${matched}')

If you want to traverse the singular elements that compose that link, you can navigate up to the root using the parent attribute of the instance.

More info in the following link

Another option would be to directly inject the Router into the component, what will directly allow you to get the current url:

@Component()
    export class TestComponent{
       constructor(private _router: Router){
         let link = _router.url();
         console.log(link.contains('ask'));
       }
    }
Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73