trim() in JavaScript

  Peter        2012-07-19 10:58:01       3,983        0    

In the past, JavaScript didn't define the trim() function for String object. This makes web programmers frustrated since they often need to implement this function themselves if they want to handle user inputs.

The new version of ECMA-262 introduces the trim() function.

15.5.4.20   String.prototype.trim ( )  
 
The following steps are taken:  
 
1.   Call CheckObjectCoercible passing the this value as its argument.  
2.   Let S be the result of calling ToString, giving it the this value as its argument.  
3.  Let T be a String value that is a copy of S with both leading and trailing white space removed. The definition of white space is the union of  WhiteSpace and LineTerminator .  
4.   Return T.  
 
NOTE  The trim function is intentionally generic; it does not require that its this value be a String object. Therefore, it  can be transferred to other kinds of objects for use as a method. 


Here are a few ways to implement the trim() function.

1. This may be the most popular way of implementing trim()

String.prototype.trim = function() { 
    return this.replace(/^\s+/g,"").replace(/\s+$/g,""); 


2 From Mootools

function trim(str){ 
    return str.replace(/^(\s|\xA0)+|(\s|\xA0)+$/g, ''); 


3. This is for jQuery, it is similar to the first one

function trim(str){ 
    return str.replace(/^(\s|\u00A0)+/,'').replace(/(\s|\u00A0)+$/,''); 


4. This method is from Steven Levithan. He finds this method is the fastest way to trim string. It is suitable for trimming long string.

function trim3(str){
    str = str.replace(/^(\s|\u00A0)+/,'');
    for(var i=str.length-1; i>=0; i--){
        if(/\S/.test(str.charAt(i))){
            str = str.substring(0, i+1);
            break;
        }
    }
    return str;
}

Source : http://justjavac.iteye.com/blog/933093

JAVASCRIPT  IMPLEMENTATION  TRIM() 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

Learn JavaScript