我如何从字符串的开始和结束删除所有空白?
当前回答
这里有一个非常简单的方法:
function removeSpaces(string){
return string.split(' ').join('');
}
其他回答
如果你已经在使用jQuery框架,那么从jQuery修剪是很方便的。
$.trim(' your string ');
我倾向于经常使用jQuery,所以用它修剪字符串对我来说是很自然的。但是否有可能出现反对jQuery的声音?:)
我知道这个问题三年前就有人问过了。现在,String.trim()是在JavaScript中原生添加的。举个例子,你可以像下面这样直接修剪,
document.getElementById("id").value.trim();
从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 ")
JavaScript修剪的通用函数是什么?
function trim(str) {
return str.replace(/^\s+|\s+$/g,"");
}
不知道有什么虫子可以藏在这里,但我用这个:
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])