Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda