3

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?

3
  • {{ key.replace(/_/g, ' ') }} is considered as angular expression. Commented Aug 30, 2016 at 10:18
  • i know. Funny thing is {{ key.replace('_', ' ') }} works fine but it only removes first instance. I need to replace all of them. Commented Aug 30, 2016 at 10:19
  • 1
    Just to provide more insights on why this doesn't work. The key.replace(/_/g, ' ') tries to use a regular expression to remove all occurences of that pattern. Here is an extract from the Angular docs You can't declare functions or create regular expressions from within AngularJS expressions. This is to avoid complex model transformation logic inside templates. Such logic is better placed in a controller or in a dedicated filter where it can be tested properly.. Ref: docs.angularjs.org/guide/expression Commented Aug 30, 2016 at 10:35

3 Answers 3

4

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Fadhly Permata and Syam Pillai
@TahreemIqbal: Glad to help you :)
4

Using angular filter is the best practice to filter from html.

Have a look at angular-filter here

.filter('customFilter', ['$filter', function ($filter) {
    return function (input) {
      if (input) {
      	return input.replace(/_/g, '');
      }
		}
}])
<th class="text-center" ng-repeat="(key, value) in filteredEL[0] ">
    {{ key | customFilter}}
 </th>

Comments

0

You can use split and join.

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

1 Comment

Please elaborate what split and join is. Or just make your answer a bit bigger.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.