我如何从字符串的开始和结束删除所有空白?
当前回答
下面是它的TypeScript格式:
var trim: (input: string) => string = String.prototype.trim
? ((input: string) : string => {
return (input || "").trim();
})
: ((input: string) : string => {
return (input || "").replace(/^\s+|\s+$/g,"");
})
如果本机原型不可用,它将回退到正则表达式。
其他回答
自IE9+以来的所有浏览器都有trim()方法用于字符串:
" \n test \n ".trim(); // returns "test" here
对于那些不支持trim()的浏览器,你可以使用MDN的这个填充:
if (!String.prototype.trim) {
(function() {
// Make sure we trim BOM and NBSP
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
String.prototype.trim = function() {
return this.replace(rtrim, '');
};
})();
}
也就是说,如果使用jQuery, $.trim(str)也是可用的,并处理undefined/null。
看到这个:
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
String.prototype.ltrim=function(){return this.replace(/^\s+/,'');};
String.prototype.rtrim=function(){return this.replace(/\s+$/,'');};
String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};
Flagrant Badassery有11个不同的修剪基准信息:
http://blog.stevenlevithan.com/archives/faster-trim-javascript
毫无疑问,基于regexp的循环比传统循环慢。
这是我个人的。这段代码太旧了!我为JavaScript1.1和Netscape 3编写了它,从那以后它只进行了轻微的更新。(最初使用String.charAt)
/**
* Trim string. Actually trims all control characters.
* Ignores fancy Unicode spaces. Forces to string.
*/
function trim(str) {
str = str.toString();
var begin = 0;
var end = str.length - 1;
while (begin <= end && str.charCodeAt(begin) < 33) { ++begin; }
while (end > begin && str.charCodeAt(end) < 33) { --end; }
return str.substr(begin, end - begin + 1);
}
有很多实现可以使用。最明显的是这样的:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
};
" foo bar ".trim(); // "foo bar"
JavaScript修剪的通用函数是什么?
function trim(str) {
return str.replace(/^\s+|\s+$/g,"");
}
从angular js项目中修剪代码
var trim = (function() {
// if a reference is a `String`.
function isString(value){
return typeof value == 'string';
}
// native trim is way faster: http://jsperf.com/angular-trim-test
// but IE doesn't have it... :-(
// TODO: we should move this into IE/ES5 polyfill
if (!String.prototype.trim) {
return function(value) {
return isString(value) ?
value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
};
}
return function(value) {
return isString(value) ? value.trim() : value;
};
})();
并将其命名为trim(" hello ")