如何修剪()angularjs中的字符串?

Sla*_*ast 19 javascript jquery angularjs

有特定角度的方式吗?如果没有,我应该使用内置的jquery来做吗?如果我应该使用内置的jquery如何在不使用$(或必要)的情况下使用trim()函数?

编辑 - 是的我知道str.trim().抱歉.我需要这个在IE 8中工作

编辑 - 至于这个问题是重复的,我特别询问如何在角度中执行此操作,其中引用的答案解释了如何在javascript,node和jquery中执行此操作.有没有办法使用角度内置的jquery来做到这一点?

编辑 - 显然答案是"AngularJS不这样做"

Zee*_*Zee 23

你为什么不简单地使用JavaScript的trim():

str.trim() //Will work everywhere irrespective of any framework.
Run Code Online (Sandbox Code Playgroud)

为了兼容<IE9使用:

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}
Run Code Online (Sandbox Code Playgroud)

在这里找到它

  • 嗯...不是无处不在...例如在 &lt;IE9 :) (2认同)

Ser*_*hiv 20

如果您只需要显示修剪后的值,那么我建议不要操纵原始字符串并使用过滤器.

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
    };
});
Run Code Online (Sandbox Code Playgroud)

然后

<span>{{ foo | trim }}</span>
Run Code Online (Sandbox Code Playgroud)


Shu*_*gam 12

在所有angularjs也是一个javascript框架之后使用javascript的trim()方法并且没有必要把$应用于trim()

例如

var x="hello world";
x=x.trim()
Run Code Online (Sandbox Code Playgroud)


小智 5

我将此代码插入标签中,并且可以正常工作:

ng-show="!Contract.BuyerName.trim()" >
Run Code Online (Sandbox Code Playgroud)