[英]How do I trim() a string in angularjs?
Is there an angular specific way? 有特定角度的方式吗? If not, should I use the built in jquery to do it?
如果没有,我应该使用内置的jquery来做吗? If I should use the built in jquery how do I get to the trim() function without using $ (or is that necessary)?
如果我应该使用内置的jquery如何在不使用$(或必要)的情况下使用trim()函数?
Edit - Yes I know about str.trim(). 编辑 - 是的我知道str.trim()。 Sorry.
抱歉。 I need this to work in IE 8
我需要这个在IE 8中工作
Edit - As far as this question being a duplicate, I am asking specifically how to do this in angular where the answer referenced explains how to do it in javascript, node and jquery. 编辑 - 至于这个问题是重复的,我特别询问如何在角度中执行此操作,其中引用的答案解释了如何在javascript,node和jquery中执行此操作。 Is there a way to do it using the built in jquery in angular?
有没有办法使用角度内置的jquery来做到这一点?
Edit - Apparently the answer is "AngularJS doesn't do this" 编辑 - 显然答案是“AngularJS不这样做”
Why don't you simply use JavaScript's trim() : 你为什么不简单地使用JavaScript的trim() :
str.trim() //Will work everywhere irrespective of any framework.
For compatibility with <IE9
use: 为了与
<IE9
兼容使用:
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
If you need only display the trimmed value then I'd suggest against manipulating the original string and using a filter instead. 如果您只需要显示修剪后的值,那么我建议不要操纵原始字符串并使用过滤器 。
app.filter('trim', function () {
return function(value) {
if(!angular.isString(value)) {
return value;
}
return value.replace(/^\s+|\s+$/g, ''); // you could use .trim, but it's not going to work in IE<9
};
});
And then 然后
<span>{{ foo | trim }}</span>
use trim() method of javascript after all angularjs is also a javascript framework and it is not necessary to put $ to apply trim() 在所有angularjs也是一个javascript框架之后使用javascript的trim()方法并且没有必要把$应用于trim()
for example 例如
var x="hello world";
x=x.trim()
我在我的标签中插入此代码,它可以正常工作:
ng-show="!Contract.BuyerName.trim()" >
JS .trim() is supported in basically everthing, except IE 8 and below. 基本上支持JS .trim(),IE 8及以下版本除外。
If you want it to work with that, then, you can use JQuery, but it'll need to be <2.0.0 (as they removed support for IE8 in the 2.xx line). 如果你希望它可以使用它,那么,你可以使用JQuery,但它需要<2.0.0(因为它们在2.xx行中删除了对IE8的支持)。
Your other option, if you care about IE7/8 (As you mention earlier), is to add trim yourself: 你的另一个选择,如果你关心IE7 / 8(如前所述),就是自己添加修剪:
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.