我如何从字符串的开始和结束删除所有空白?
当前回答
我有一个库,使用修剪。所以通过使用下面的代码来解决它。
String.prototype.trim = String.prototype.trim || function(){ return jQuery.trim(this); };
其他回答
从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 ")
我的使用一个regex来寻找需要修剪的情况,并使用regex的结果来确定所需的子字符串边界:
var illmatch= /^(\s*)(?:.*?)(\s*)$/
function strip(me){
var match= illmatch.exec(me)
if(match && (match[1].length || match[2].length)){
me= me.substring(match[1].length, p.length-match[2].length)
}
return me
}
其中的一个设计决策是使用子字符串执行最终捕获。/ \ ?://(捕获中间项)并且替换片段变成:
if(match && (match[1].length || match[3].length)){
me= match[2]
}
我在这些建议中做了两个性能赌注:
子字符串实现复制原始字符串的数据吗?如果是这样,在第一种情况下,当一个字符串需要修整时,会有两次遍历,第一次在正则表达式中(希望是部分的),第二次在子字符串提取中。希望子字符串实现只引用原始字符串,这样像substring这样的操作几乎是免费的。交叉手指 正则表达式impl中的捕获有多好?中间项,也就是输出值,可能会很长。我还没有准备好银行所有的regex impls的捕获不会阻止几百KB的输入捕获,但我也没有测试(太多的运行时,对不起!)第二个ALWAYS运行捕获;如果你的引擎可以做到这一点而不受影响,也许可以使用上面的一些技巧,那就一定要使用它!
如果使用jQuery,请使用jQuery.trim()函数。例如:
if( jQuery.trim(StringVariable) == '')
我为trim写了这个函数,当时.trim()函数在2008年的JS中还不可用。一些旧的浏览器仍然不支持.trim()函数,我希望这个函数可以帮助到一些人。
修剪函数
function trim(str)
{
var startpatt = /^\s/;
var endpatt = /\s$/;
while(str.search(startpatt) == 0)
str = str.substring(1, str.length);
while(str.search(endpatt) == str.length-1)
str = str.substring(0, str.length-1);
return str;
}
解释:函数trim()接受一个字符串对象,删除任何开头和结尾的空格(空格、制表符和换行符),并返回经过修剪的字符串。您可以使用此函数修改表单输入,以确保发送的数据是有效的。
函数的调用方法如下所示。
form.elements[i].value = trim(form.elements[i].value);
String.prototype.trim = String.prototype.trim || function () {
return this.replace(/^\s+|\s+$/g, "");
};
String.prototype.trimLeft = String.prototype.trimLeft || function () {
return this.replace(/^\s+/, "");
};
String.prototype.trimRight = String.prototype.trimRight || function () {
return this.replace(/\s+$/, "");
};
String.prototype.trimFull = String.prototype.trimFull || function () {
return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, "").replace(/\s+/g, " ");
};
无耻地从马特·杜雷格那里偷来的。