conan
conan

Reputation: 1337

check the url has a string after a fixed word jquery javascript?

I have the the url http://ste.com/members/username/, I had search stackoverflow for the following code which is great. but I face the issue is that, I cannot change the username all the time, so I cannot put the fixed username. I was trying to put 'members',but it will affect other pages. So how can I check if my url contain any string after members/, thanks!

if (window.location.href.indexOf("username") > -1) {
    $('html, body').animate({
        scrollTop: $('#item-nav').offset().top
    }, 'slow');
}

Upvotes: 1

Views: 204

Answers (2)

John R
John R

Reputation: 2791

This is not a generic and appropriate fix. But you can try this way also using substring().

var link = window.location.href;
if(((link.substring(link.indexOf("members/") +8)))){
    //your code
   }

Hope this helps!

Upvotes: 1

Chris Hanson
Chris Hanson

Reputation: 731

I'd use regex here.

if (window.location.href.match(/members\/\w+/))  {

This checks if the href matches the string 'members/' and then at least 1 word character after that.

You can read more about regular expressions here https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

Upvotes: 4

Related Questions