Javascript 如何使用 jQuery 的 trim() 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13681187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use jQuery's trim() function
提问by Gideon
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? Here is my code:
我不知道如何翻译我的函数以使用那个版本的修剪(我以为我已经在使用 jQuery),有人可以建议吗?这是我的代码:
$('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.
但这并不好。
回答by Tetaxa
$.trim(val.replace('Please Select', ''))
回答by Elias Van Ootegem
IE8 doesn't have a native trimmethod, 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 ($.trimcalls 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. Basically, it's the same operation, but it shouldbe a marginally more efficient, because jQuery does a bunch of checks to any string passed to the jQuery constructor ($())
增强原型的好处是您没有创建新 jQuery 对象的额外开销,而使用原型方法依赖于 JS 将字符串包装在本机 String 对象中并将方法应用于该对象。基本上,它是相同的操作,但它的效率应该略高一些,因为 jQuery 对传递给 jQuery 构造函数 ( $()) 的任何字符串进行大量检查

