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

123
Vistas
Revers a string word by word without using inbuilt function in javascript
function reverse1(str) {
  let r = "";
  for (let i = str.length - 1; i >= 0; i--) {
    r += str[i];
  }
  return r;
}

console.log(reverse1("I like this program very much"));

output: // hcum yrev margorp siht ekil I

but expected output: I ekil siht margorp yrev hcum

please can any one answer this....???

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

0

Traverse the original string and reverse the individual words.

function reverseUtil(str) {
    let r = "";
    for (let i = str.length - 1; i >=0; i--) {
        r += str[i];
    }
    return r;
}

function reverse1(str) {
    let r = "", tmp = "";
    for (let i = 0; i < str.length; i++) {
        if (str[i] == ' ') {
            r += reverseUtil(tmp) + ' ';
            tmp = "";
        } else tmp += str[i];
    }

    // last word
    r += reverseUtil(tmp);

    return r;
}

console.log(reverse1("I like this program very much"));

about 4 years ago · Juan Pablo Isaza Denunciar

0

You are reversing the whole string. If you want to use a single function and assuming the string contains spaces only, you can loop through every character of the string.

If you encounter a space, you can append that to the result. If you encounter another character, you can prepend that to a temporary string to build a reversed version of the word.

Then append the reversed version of word to the result when the next character is either a space or when it is the last character in the iteration.

function reverse1(str) {
  let result = "", tmp = "";
  for (let i = 0; i < str.length; i++) {
    if (str[i] === ' ') {
      result += ' '; continue;
    }
    tmp = str[i] + tmp;
    if (str[i + 1] === undefined || str[i + 1] === ' ') {
      result += tmp; tmp = "";
    }
  }
  return result;
}

console.log(reverse1("I like this program very much"));
console.log(reverse1("    I like this program very much   "));
console.log(reverse1("abc"));

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