Aviv M Aviv M - 6 months ago 58
AngularJS Question

How can I remove all string spaces in AngularJS binding?

I try to do this:

<div id="{{mystring.replace(/[\s]/g, \'\')}}"></div>


but its not working. "mystring" is an object on
$scope
with string like "my string is this" with spaces I want to remove from the view.

Answer

Just create a dedicated filter :

angular.module('filters.stringUtils', [])

.filter('removeSpaces', [function() {
    return function(string) {
        if (!angular.isString(string)) {
            return string;
        }
        return string.replace(/[\s]/g, '');
    };
}])

and call it like :

<div id="{{'hi there'| removeSpaces}}"></div>
Comments