Tuesday 30 August 2016

AngularJS String Replace filter in the Template File

Please find follow the below steps to replace the string on the Template file using AngularJS filter:

1. Create the filter file called string-replace.js and add the following code.
myapp.filter('stringReplace', [ function() {
    return function(input, search, replace) {
        input = input.split(search);
        
        var x;
        var result = '';
        var prefix = '';
        for (x in input ) {
            result += prefix + input[x];
            prefix = replace;
        }

        return result;
        //return input.replace(search, replace);
    };
}]);

2. Then, in html template file, adopt the below example to use the filer.
{{your_string_variable_here | stringReplace:'searchParameterHere':'replaceParameterHere'}}

Example:
{{"GLOBAL_WARMING_NEEDS_TO_CONTROL_BY_EVERYONE" | stringReplace:'_':'-'}}

Output: GLOBAL-WARMING-NEEDS-TO-CONTROL-BY-EVERYONE