SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast
    Join Date
    Jul 2004
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Javascript String doesn't have trim method ?

    I was trying:
    Code:
    <script>
    
    function testtrim(value) {
    	
    	alert(value.trim());
    	
    }
    
    testtrim("Alex ");
    </script>
    The javascript don't work, my firebugs says:[value.trim is not a function]
    how to simulate an trim function ?

    thanks.

  2. #2
    He's No Good To Me Dead silver trophybronze trophy stymiee's Avatar
    Join Date
    Feb 2003
    Location
    Slave I
    Posts
    23,449
    Mentioned
    1 Post(s)
    Tagged
    1 Thread(s)
    Code:
    String.prototype.trim = function()
    {
        return this.replace(/^\s*|\s*$/g,'');
    }

  3. #3
    SitePoint Enthusiast
    Join Date
    Jul 2004
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by stymiee View Post
    Code:
    String.prototype.trim = function()
    {
        return this.replace(/^\s*|\s*$/g,'');
    }
    hum... it cool... the javascript allow you add new method dynamically ?

    String.prototype.trim what mean it ?

    thanks.

  4. #4
    SitePoint Zealot Skibum1321's Avatar
    Join Date
    Jun 2003
    Location
    Malden, MA
    Posts
    142
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes, as with any programming language you can define your own functions. The one below is actually from the prototype javascript library. If you use that library (just a bunch of prewritten functions to make your life easier), then you will get that function and many others.
    Keith Rousseau

  5. #5
    He's No Good To Me Dead silver trophybronze trophy stymiee's Avatar
    Join Date
    Feb 2003
    Location
    Slave I
    Posts
    23,449
    Mentioned
    1 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by ualex View Post
    hum... it cool... the javascript allow you add new method dynamically ?

    String.prototype.trim what mean it ?

    thanks.
    By assigning the trim function to the String prototype you are making it available to all strings in your code. Do a search for "prototype" in javascript. It's good stuff to know.


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
  •