$.trim(value);
上面的jQuery代码会修剪文本。我需要使用Javascript修剪字符串。
我想:
link_content = " check ";
trim_check = link_content.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,'');
如何在JavaScript中使用修剪?相当于jQuery的$.trim()
?
$.trim(value);
上面的jQuery代码会修剪文本。我需要使用Javascript修剪字符串。
我想:
link_content = " check ";
trim_check = link_content.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,'');
如何在JavaScript中使用修剪?相当于jQuery的$.trim()
?
的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, '');
};
}
})();
这里有一些功能,可以帮助试戴:
从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, "");
},