Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!