SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast alokjain_lucky's Avatar
    Join Date
    Feb 2008
    Location
    India
    Posts
    33
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    regular expression for substring

    Hi,

    can someone please tell me what will be the regular expression for this line:

    Code JavaScript:
    var id = $(this).attr("href").substring( $(this).attr("href").lastIndexOf('#'), $(this).attr("href").length);

    Basically it gets the string after # in href attribute of clicked anchor tag.

    Thanks.

  2. #2
    SitePoint Enthusiast TriLLi's Avatar
    Join Date
    Feb 2010
    Location
    BiH, Bugojno
    Posts
    86
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,

    you can get anything in href after # with next regular expression #(\b[^\"]*)

    I hope this helps

  3. #3
    SitePoint Enthusiast alokjain_lucky's Avatar
    Join Date
    Feb 2008
    Location
    India
    Posts
    33
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks

    I tried this:

    Code JavaScript:
    var id = $(this).attr("href").match(#(\b[^\"]*));

    But it's giving me error

    Actually i have created following function to scroll to the named anchors, this function is working fine, i am just trying to improve and shorten the code.

    Code JavaScript:
    $(document).ready(function() {
    	 $('a[href^=#]').click(function(){
    			var id = $(this).attr("href").substring( $(this).attr("href").lastIndexOf('#'), $(this).attr("href").length);
    			$('html,body').animate({scrollTop: $(id).offset().top},'slow');
    			return false;
    		});
    });

    Any other suggestions for improvement are also welcome.

    Thanks.

  4. #4
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,070
    Mentioned
    153 Post(s)
    Tagged
    2 Thread(s)
    No offence, but regex won't improve that code, only make it slower.
    indexOf and .length are way faster than regex.

    If anything I would make it $('html,body').stop(true).animate( ... );

    to make sure previous animations of body and html stop immediately and start the new animation right away, to avoid a long queue of scrolling up and down and up and down and ....

    Rémon - Hosting Advisor

    SitePoint forums will switch to Discourse soon! Make sure you're ready for it!

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •