[英]How to use jQuery's trim() function
As discussed in many questions on stack - IE 8 wont accept .trim()
, but the jQuery framework takes care of that. 正如在堆栈上的许多问题中所讨论的那样 - IE 8不会接受
.trim()
,但是jQuery框架会处理这个问题。
I don't know how to translate my function to use that version of trim (I thought I was already using jQuery), could someone advise? 我不知道如何翻译我的函数来使用那个版本的修剪(我以为我已经在使用jQuery),有人可以建议吗? Here is my code:
这是我的代码:
$('input').val(function(index, val){
return val.replace('Please Select', '').trim();
});
This is designed to replace the string with nothing. 这是为了无需替换字符串。
I've tried: 我试过了:
$('input').val(function(index, val){
return val.replace('Please Select', '')$.trim();
});
but that was no good. 但那并不好。
$.trim(val.replace('Please Select', ''))
IE8 doesn't have a native trim
method, generally, I just augment the prototype: IE8没有原生
trim
方法,一般来说,我只是增加了原型:
if (!String.prototype.trim)
{
String.prototype.trim = function()
{
return this.replace(/^\s+|\s+$/g,'');
};
}
This is the shortest regex to trim a string, but I have heard it say that .replace(/^\\s\\s*/,'').replace(/\\s*\\s$/,'')
is (marginally) faster... the choice is yours 这是修剪字符串的最短正则表达式,但我听说它说
.replace(/^\\s\\s*/,'').replace(/\\s*\\s$/,'')
是(略) )更快......选择权在你手中
If you really want to use jQuery for this, of course, you'll have to make the target string the context of the called method ( $.trim
calls the method on $
=== the jQuery object), so make the String a jQ object: 如果你真的想为此使用jQuery,当然,你必须使目标字符串成为被调用方法的上下文(
$.trim
调用$
=== jQuery对象的方法),所以使String成为一个jQ对象:
$(' foo bar ').trim();//returns "foo bar"
//compared to augmented prototype:
' foo bar '.trim();//returns "foo bar"
The benefit of an augmented prototype is that you don't have the additional overhead of creating a new jQuery object, whereas using the prototype-approach relies on JS to wrap the string in a native String object and apply the method to that. 增强原型的好处是您没有创建新jQuery对象的额外开销,而使用prototype-approach依赖于JS将字符串包装在本机String对象中并将该方法应用于该对象。 Basically, it's the same operation, but it should be a marginally more efficient, because jQuery does a bunch of checks to any string passed to the jQuery constructor (
$()
) 基本上,它是相同的操作,但它应该是一个稍微更高效,因为jQuery对传递给jQuery构造函数的任何字符串(
$()
)进行了大量检查
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.