简体   繁体   中英

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? If I should use the built in jquery how do I get to the trim() function without using $ (or is that necessary)?

Edit - Yes I know about str.trim(). Sorry. I need this to work in 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. Is there a way to do it using the built in jquery in angular?

Edit - Apparently the answer is "AngularJS doesn't do this"

Why don't you simply use JavaScript's trim() :

str.trim() //Will work everywhere irrespective of any framework.

For compatibility with <IE9 use:

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

Found it Here

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()

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.

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).

Your other option, if you care about IE7/8 (As you mention earlier), is to add trim yourself:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM