Issue
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
Solution
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>
Answered By - Lex
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.