Tahreem Iqbal Tahreem Iqbal - 3 months ago 14
AngularJS Question

str.replace not working inside html

I need to replace all

_
from a string in my angular app. In my controller, following code gives correct result:

alert("this_is_string_".replace(/_/g, " "));


But when I put the same code in my html file like this:

<th class="text-center" ng-repeat="(key, value) in filteredEL[0] ">
{{ key.replace(/_/g, ' ') }}
</th>


it gives following error:

Error: [$parse:syntax] Syntax Error: Token '/' not a primary expression at column 13 of the expression [key.replace(/_/g, ' ')] starting at [/_/g, ' ')]


So, how can I use replace function that replaces all required instances inside the html?

Answer

Just create a dedicated filter :

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

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

and call it like :

<div id="{{'hi_there'| removeUnderscores}}"></div>