trim() in JavaScript

Summary

JavaScript's String.prototype.trim() function, now standardized in ECMA-262, provides a built-in solution for removing leading and trailing whitespace from strings. This addition resolves a common developer challenge, as prior to its introduction, custom implementations were necessary, often utilizing regular expressions to strip characters like spaces and line terminators. The specification details a process of coercing the value to a string and then removing all leading and trailing whitespace, emphasizing its generic design which allows it to be applied to various object types. While several regex-based alternatives existed, including those from popular libraries like Mootools and jQuery, some developers also created optimized versions, such as Steven Levithan's method, for enhanced performance on longer strings.

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

  COMMENTS

0

No comment for this article.