Reverse a string without .reverse (); in JS

-1

Well it turns out that I have to reverse a String in JS but the method .reverse (); It does not work in my case.

function invertir_nums(numeros, numeros_i){
  numeros_i = numeros.reverse();
}

The problem is that it does not invert the Array well and orders it as it pleases. So try this but it does not work either.

function invertir_nums(numeros, numeros_i){
  for (var i = 0; i < 6; i++){
    numeros_i[i] = numeros[6-i];
  }

}
    
asked by Franco Moreno 02.01.2019 в 16:42
source

5 answers

3

A simple way to do what you are looking for is to iterate the word you want to reverse in reverse.

For example;

var cadena = "Hola, mi nombre es Juan";
var cadenarevertida = "";
   
//Itero la cadena de manera inversa
for(var i = cadena.length-1; i>=0; i--)
{
  //Voy concatenando el valor a la cadena resultado
  cadenarevertida += cadena[i];
}
console.log(cadenarevertida);
    
answered by 02.01.2019 в 16:53
2

As you say in your case, .reverse() does not work, this is because what you invest is not an array but a string. If you want to use this method with a string you can try doing something like:

    function invertir_nums(numeros) { 
        return numeros.split('').reverse().join('')
    }
    
answered by 02.01.2019 в 17:07
1

you can do it like this:

    // funccion simple 
    function rev(str) {
        return str.split("").reverse().join("");
    }
    
   //sin reverse
    function revS(str) {
    return (str === '') ? '' : revS(str.substr(1)) + str.charAt(0);
   }
    //agregandolo un metodo a String
    String.prototype.rev = function(){
      return this.split("").reverse().join("");
    }


    console.log(rev("hello"));
    console.log(revS("hello"));
    console.log("hello".rev());
  

The reason why the reverse() method does not work for you is because it's just to reverse fixes!

    
answered by 02.01.2019 в 17:08
0

As Cardeol commented, your logic does not make much sense

function invertir_nums(numeros, numeros_i){
var j=0;                   //variable para el índice de numeros_i
for (var i = 6; i <=0; i--){          //recorres tu array de atrás para adelante
    numeros_i[j++] = numeros[i];        //asignas de adelanta para atrás
  }
}

I do not program in javascript, if I have an error in syntax, please correct it.

    
answered by 02.01.2019 в 16:53
0

I have a way of doing it, with a somewhat different approach.

Once for a job interview, they asked me for something similar.

Here's my code to see if it serves as an answer:

function reverseString(s) {
// Funcion reverseString(s) => string
//  s: string que deseamos invertir
//  devuelve: String

    const len = s.length
    // verificamos si el tamaño del string es par o impar
    const isOdd = len % 2;
    // calculamos la mitad del string para poder iterar solo hasta alli (esto es por mejorar un poco la eficiencia)
    // si es impar debemos redondear (redondeo por defecto o redondeo hacia abajo) 
    // eso significa que el carácter del medio (central) no cambia.
    const middle = isOdd ? Math.floor(len / 2) : len / 2;

    // Ahora guardamos el carácter central si el tamaño del string es impar,
    // en caso que sea par, no existe carácter central
    let center = isOdd ? s[middle] : undefined;
    let head = '';
    let tail = '';
    for (let i = 0 ; i < middle ; i++) {
        // Aqui básicamente vamos llenando la cabezera y la cola de forma invertida.
        // Leemos el string original de atrás hacia adelante y lo vamos almacenando.
        // Nótese que 'head' se llena desde el final hasta la mitad y 'tail' se llena
        // desde la mitad hasta el inicio.
        
        head = head.concat(s[len - (i + 1)]);
        tail = tail.concat(s[middle - (i + 1)]);
    } // fin bucle for

    // Ahora podemos construir nuestro string invertido usando head, center y tail
    const str = center ? head.concat(center.concat(tail)) : head.concat(tail); 
    // Finalmente devolvemos el resultado
    return str;
} // fin funcion

// Un par de pruebas usando tamaños par e impar:
let reversedString = '';
const evenString = 'QWERTY';
const oddString = 'QWERTYU'

reversedString = reverseString(evenString);
console.log(evenString);
console.log(reversedString);

reversedString = reverseString(oddString);
console.log(oddString);
console.log(reversedString);

Greetings.

    
answered by 04.01.2019 в 02:52