Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

109
Vistas
Reverse a string using two-pointer method in JS

I am trying to reverse a string. I am aware of .reverse function and other methods in Js to do so, but i wanted to do it this two-pointer method.

The problem is the string is not getting updated. Is there anything i am not aware of strings. Whats wrong here ?

function reverseString(s) {
  let lengthOfStr = 0;

  if ((s.length - 1) % 2 == 0) {
    lengthOfStr = (s.length - 1) / 2
  } else {
    lengthOfStr = ((s.length - 1) / 2) + 1;
  }
  let strLengthLast = s.length - 1;
  for (let i = 0; i <= lengthOfStr; i++) {
    let pt1 = s[i];
    let pt2 = s[strLengthLast];

    s[i] = pt2;
    s[strLengthLast] = pt1;
    console.log('----', s[i], s[strLengthLast]);
    strLengthLast--;
  }
  return s;
}
console.log(reverseString('hello'));

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Unlike in C, strings in JavaScript are immutable, so you can't update them by indexing into them. Example:

let s = 'abc';
s[1] = 'd';
console.log(s); // prints abc, not adc

You'd need to do something more long-winded in place of s[i] = pt2;, like s = s.substring(0, i) + pt2 + s.substring(i + 1);, and similarly for s[strLengthLast] = pt1; (or combine them into one expression with 3 calls to substring).

about 4 years ago · Juan Pablo Isaza Denunciar

0

I'm not sure why it doesnt update the string, but if you handle the replacement as an array/list it works as follows:

function reverseString(s) {
  let lengthOfStr = 0;
  sSplit = s.split("");

  if ((s.length - 1) % 2 === 0) {
    lengthOfStr = (s.length - 1) / 2
  }
  else {
    lengthOfStr = ((s.length - 1) / 2) + 1;
  }
  let strLengthLast = s.length - 1;
  for (let i = 0; i <= lengthOfStr; i++) {
    let pt1 = sSplit[i];
    let pt2 = sSplit[strLengthLast];

    sSplit[i] = pt2;
    sSplit[strLengthLast] = pt1;
    console.log('----', sSplit[i], sSplit[strLengthLast],sSplit);
    strLengthLast--;
  }
  return sSplit.join("");
}
console.log(reverseString('Hello'));

returns: Hello => olleH

about 4 years ago · Juan Pablo Isaza Denunciar

0

As covered in comment, answers and documentation, strings are immutable in JavaScript.

The ability to apparently assign a property value to a primitive string value results from early JavaScript engine design that temporarily created a String object from primitive strings when calling a String.prototype method on the primitive. While assigning a property to the temporary object didn't error, it was useless since the object was discarded between calling the String method and resuming execution of user code.

The good news is that this has been fixed. Putting

 "use strict";

at the beginning of a JavaScript file or function body causes the compiler to generate a syntax error that primitive string "properties" are read-only.

There are many ways of writing a function to reverse strings without calling String.prototype.reverse. Here's another example

function strReverse(str) {
    "use strict";
     let rev = [];
     for( let i = str.length; i--;) {
         rev.push(str[i]);
     }
     return rev.join('');
}

console.log( strReverse("Yellow") );
console.log( strReverse("").length);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda