我如何从字符串的开始和结束删除所有空白?
当前回答
你可以使用纯JavaScript来实现:
function trimString(str, maxLen) {
if (str.length <= maxLen) {
return str;
}
var trimmed = str.substr(0, maxLen);
return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…';
}
// Let's test it
sentenceOne = "too short";
sentencetwo = "more than the max length";
console.log(trimString(sentenceOne, 15));
console.log(trimString(sentencetwo, 15));
其他回答
自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,' ');};
使用原生JavaScript方法:String.trimLeft(), String.trimRight()和String.trim()。
在IE9+和所有其他主要浏览器中都支持String.trim():
' Hello '.trim() //-> 'Hello'
String.trimLeft()和String.trimRight()是非标准的,但除IE之外的所有主流浏览器都支持
' Hello '.trimLeft() //-> 'Hello '
' Hello '.trimRight() //-> ' Hello'
IE的支持很容易与polyfill:
if (!''.trimLeft) {
String.prototype.trimLeft = function() {
return this.replace(/^\s+/,'');
};
String.prototype.trimRight = function() {
return this.replace(/\s+$/,'');
};
if (!''.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
}
如果你已经在使用jQuery框架,那么从jQuery修剪是很方便的。
$.trim(' your string ');
我倾向于经常使用jQuery,所以用它修剪字符串对我来说是很自然的。但是否有可能出现反对jQuery的声音?:)
使用简单的代码
var str = " Hello World! ";
alert(str.trim());
浏览器支持
Feature Chrome Firefox Internet Explorer Opera Safari Edge
Basic support (Yes) 3.5 9 10.5 5 ?
为旧浏览器添加原型
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
如果使用jQuery,请使用jQuery.trim()函数。例如:
if( jQuery.trim(StringVariable) == '')
推荐文章
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- 如何删除表中特定列的第一个字符?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 我如何等待一个承诺完成之前返回一个函数的变量?