2011-06-01 28 views
2
$.trim(value); 

上面的jQuery代碼會修剪文本。我需要使用Javascript修剪字符串。

我想:

link_content = " check "; 
trim_check = link_content.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,''); 

如何在JavaScript中使用修剪?相當於jQuery的$.trim()

回答

9

的JavaScript 1.8.1包括對String對象的裝飾方法。此代碼將在沒有本地實現的瀏覽器中添加對修剪方法的支持:

(function() { 
    if (!String.prototype.trim) { 
     /** 
     * Trim whitespace from each end of a String 
     * @returns {String} the original String with whitespace removed from each end 
     * @example 
     * ' foo bar '.trim(); //'foo bar' 
     */ 
     String.prototype.trim = function trim() { 
      return this.toString().replace(/^([\s]*)|([\s]*)$/g, ''); 
     }; 
    }  
})(); 
1

從jQuery源:

// Used for trimming whitespace 
    trimLeft = /^\s+/, 
    trimRight = /\s+$/, 

// Use native String.trim function wherever possible 
trim: trim ? 
function(text) { 
    return text == null ? 
     "" : 
     trim.call(text); 
} : 
// Otherwise use our own trimming functionality 
function(text) { 
    return text == null ? "" : text.toString().replace(trimLeft, "").replace(trimRight, ""); 
},