问题描述
|
$.trim(value);
上面的jquery代码将修剪文本。我需要使用Javascript修剪字符串。
我试过了:
link_content = \" check \";
trim_check = link_content.replace(/(?:(?:^|\\n)\\s+|\\s+(?:$|\\n))/g,\'\').replace(/\\s+/g,\'\');
如何在JavaScript中使用trim?相当于jQuery的$.trim()
?
解决方法
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,\'\');
};
}
})();
, 从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,\"\" );
},
, 以下是一些可能有助于尝试的功能:
http://www.webtoolkit.info/javascript-trim.html