0

I'm trying to use a filter that reverses a string, this is my code:

app.filter("revertir", function(){ return function(input){ var u = input.length-1; console.log("ENTRA: "+input); for(var i=0;i<input.length/2;i++){ var temp = input[i]; input[i] = input[u]; input[u] = temp; u--; } return input; }; }); 

I inject this filter into my controller, and it's thrown properly, but I'm not getting the text reversed; it shows up exactly as the input string.

Where's the problem? This exact script for reversing works perfect in a Java test program.

1
  • JavaScript strings are immutable - you can read the nth character using array syntax, but not write to it. Commented Apr 15, 2016 at 9:11

2 Answers 2

2

Another way to implement it :

var app = angular.module("MyApp", []); app.filter("reverse", function() { return function(input) { return ( (input || '').split('').reverse().join('')); }; });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="MyApp"> write here: <input ng-model="strIn" ng-init="strIn='Hello Wordl!'" /> <p>output reversed : {{ strIn | reverse }}</p> </div>

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

Comments

0

pretty common:

var app = angular.module("MyApp", []); app.filter("reverse", function() { return function(input) { var result = ""; input = input || ""; for (var i=0; i<input.length; i++) { result = input.charAt(i) + result; } return result; }; }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.