我如何从字符串的开始和结束删除所有空白?
当前回答
不知道有什么虫子可以藏在这里,但我用这个:
var some_string_with_extra_spaces=" goes here "
console.log(some_string_with_extra_spaces.match(/\S.*\S|\S/)[0])
或者这个,如果文本包含回车:
console.log(some_string_with_extra_spaces.match(/\S[\s\S]*\S|\S/)[0])
另一个尝试:
console.log(some_string_with_extra_spaces.match(/^\s*(.*?)\s*$/)[1])
其他回答
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);
}
使用原生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的声音?:)
如果使用jQuery,请使用jQuery.trim()函数。例如:
if( jQuery.trim(StringVariable) == '')
有很多实现可以使用。最明显的是这样的:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
};
" foo bar ".trim(); // "foo bar"