SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast 8080a's Avatar
    Join Date
    Sep 2007
    Location
    Austin, TX
    Posts
    25
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    myString.search is not a function? Confused noob.

    I'm sure there's something basic I'm overlooking here, but could someone please point out why firebug keeps telling me "myString.search is not a function"?

    Code JavaScript:
    	function restrict_product_links()
    		{
    		var myString=window.location;
    		var test=myString.search("products.cfm");
    		if(test != -1)
    			{
    			document.write("PRODUCTS");
    			}
    		}

  2. #2
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    I'm no JS guru (just browsing the forums really) so I may be wrong, but window.location isn't a string.

    window.location is an object with properties such as href, pathname etc.

    So, you could probably use:
    Code javascript:
    function is_products_page(){
        var position = window.location.pathname.indexOf("products.cfm");
        return(position != -1);
    }
    function restrict_product_links(){
        if(is_products_page()){
            document.write("PRODUCTS");
        }
    }

    By the way, search() seems to be a regex pattern matcher. indexOf would therefore be more efficient as it searches for flat strings.
    Last edited by Jake Arkinstall; May 8, 2009 at 11:07. Reason: Split product-page identifier to its own function
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  3. #3
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    window.location has a toString() method, which means javascript will sometimes automatically convert this object into a string for you(when you try to use it as a string, javascript can usually figure it out, just not in this case). You can also assign a string value to it and it works. So you probably thought it was a string, but like arkinstall pointed out, its not. This is kinda some behind the scenes functionality that's non obvious.

    You could have also done
    Code:
    var myString=window.location.toString();
    // or
    var myString=window.location + "";// concat an empty string, which forces toString() to be called on any non-string operands.
    indexOf() was more suitable btw.


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
  •