Tahreem Iqbal Tahreem Iqbal - 1 year ago 188
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, ' ') }}

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 Source

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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download