1

Here I have a string with spaces, and I would like to replace the space(s) to a single dash '-'.

var card = "A World Elite Warrior";

console.log("card = " + card.toLowerCase().replace(/ /g,'-'));

The output is a-world-elite-warrior, but I just want to use it in the html template as a angularjs expression like this:

<img ng-src="images/cards/{{card.toLowerCase().replace(/ /g,'-')}}.png"

And it can not work, the error message is:

Error: [$parse:syntax] Syntax Error: Token '/' not a primary expression at column 61 of the expression

2 Answers 2

2

AngularJS doesn't support regex in the view. To get around this you can write a simple filter to apply your regex replacement. Here's an example of how you might do this in your case.

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.card = "A World Elite Warrior";
    console.log("card = " + $scope.card.toLowerCase().replace(/ /g, '-'));
  })
  .filter('dashes', function() {
    return function(input) {
      input = input || '';
      return input.toLowerCase().replace(/ /g, '-');
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  {{ card | dashes }}
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

I did just like you suggested. it works well, thank you.
0

Another approach would be to create a $scope function that carries out the regular expression. You would then just call the function from your view:

$scope.cardChange = function() {
    return $scope.card.toLowerCase().replace(/ /g,'-');
};
<img ng-src="images/cards/{{cardChange()}}.png"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.