在 JavaScript 中修剪字符串? [英] Trim string in JavaScript?
本文介绍了在 JavaScript 中修剪字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 JavaScript 中修剪字符串?也就是说,如何在 JavaScript 中去除字符串开头和结尾的所有空格?
How do I trim a string in JavaScript? That is, how do I remove all whitespace from the beginning and the end of the string in JavaScript?
推荐答案
自 IE9+ 以来的所有浏览器都有 trim()
字符串方法:
All browsers since IE9+ have trim()
method for strings:
"
test
".trim(); // returns "test" here
对于那些不支持 trim()
的浏览器,你可以使用来自 MDN:
For those browsers who does not support trim()
, you can use this polyfill from MDN:
if (!String.prototype.trim) {
(function() {
// Make sure we trim BOM and NBSP
var rtrim = /^[suFEFFxA0]+|[suFEFFxA0]+$/g;
String.prototype.trim = function() {
return this.replace(rtrim, '');
};
})();
}
也就是说,如果使用 jQuery
,$.trim(str)
也可用并处理 undefined/null.
That said, if using jQuery
, $.trim(str)
is also available and handles 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(/(?:(?:^|
)s+|s+(?:$|
))/g,'').replace(/s+/g,' ');};
这篇关于在 JavaScript 中修剪字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文