$.trim(value);
上面的jquery代码会修剪文本。我需要使用Javascript修剪字符串。
我试过了:
link_content = " check ";
trim_check = link_content.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,'');
如何在javascript中使用trim?相当于$.trim()
的jQuery?
答案 0 :(得分:9)
JavaScript 1.8.1包含String对象的trim方法。此代码将在没有本机实现的浏览器中添加对trim方法的支持:
(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 :(得分: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, "" );
},
答案 2 :(得分:0)
以下是一些可能有助于尝试的功能: