How can I remove all string spaces in AngularJS binding?

If you simply need it in one or two places it may be easier to split and join:

$scope.boundString = 'this is a string with spaces'

with that you could do in your template:

<span>my string is: {{ boundString.split(' ').join('') }}</span>

and you would get:

my string is: thisisastringwithoutspaces

another approach that has been mentioned is the regex version ('g' is for global):

<span>my string is: {{ boundString.replace(/ /g, '') }}</span>

I guess the point is that you can do whatever you want to a string within an expression. These examples are bad convention with respect to Angular dirty-checking. In Angular, bound functions (string.replace, string.split) get evaluated differently opposed to a specified value (string, boolean) when bound to a template's expression. The result of a bound function must be evaluated before Angular knows whether or not to update the DOM. This can be costly over a large app. I would suggest using another variable to track the un-spaced value:

$scope.noSpaces = $scope.boundString.replace(/ /g, '');

HTML:

<span>{{ noSpaces }}</span>

This way, when a digest loop is triggered, Angular will check if noSpaces has changed as opposed to evaluating boundString.replace(/ /g, '').

What if you are ng-repeating? Good question.

for (var idx = 0, idx < $scope.boundIterable.length, i++) {
    $scope.boundIterable[i].noSpaces = $scope.boundIterable[i].boundString.replace(/ /g, '');
}

HTML:

<ul ng-repeat="iterable in boundIterable">
    <li>{{ iterable.noSpaces }}</li>
</ul>

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>

Tags:

Angularjs