How can I remove all string spaces in AngularJS binding?

前端 未结 7 933
南方客
南方客 2020-12-29 06:09

I try to do this:

but its not working. \"mystring\" is an object on

相关标签:
7条回答
  • 2020-12-29 06:52

    The directive mentioned works pretty well. But if you want to remove spaces for smaller texts, you can use

    .split(" ").join("")
    

    This replaces the complete spaces unlike .replace(" ","") which replaces only the first space.

    0 讨论(0)
  • 2020-12-29 06:55

    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>
    
    0 讨论(0)
  • 2020-12-29 06:55

    How about {{ string.trim() }}?

    Source

    0 讨论(0)
  • 2020-12-29 06:55
    removeSpaces() {
      originalText ="hi! here i'm";
      removedSpacesText = originalText.split(" ").join("");
    }
    
    0 讨论(0)
  • 2020-12-29 06:57

    You can do it by using replace():

    {{mystring.replace(" ","")}}
    

    that's it I hope so.

    0 讨论(0)
  • 2020-12-29 07:08

    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>
    
    0 讨论(0)
提交回复
热议问题