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

442
Views
Palindrome checker does not function properly with "almostomla"

function palindrome(str) {
  const forward = str.replace(/[^a-zA-Z ]/g, "").toUpperCase()
  const reversed = str.replace(/[^a-zA-Z ]/g, "").toUpperCase()
  for (let i = 0; i < forward.length; i++) {
    for (let k = reversed.length - 1; k >= 0; k--) {
      if (forward[i] === reversed[k]) {
        return true
      } else {
        return false
      }
    }
  }
}

console.log(palindrome("almostomla"));

Why is this not working?? does my loop just creates a new "s"?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You don't need nested loops, that will compare every character with every other character. You just want to compare the first character with the last character, 2nd character with 2nd-to-last character, and so on. So there should just be a single loop that increments i and decrements k in lock step.

You shouldn't return true when you find a match, because there could be later characters that don't match. Return false when you find a mismatch, and return true if you make it through the loop without returning.

You don't need both forward and reversed variables, since they're the same. Just convert the input string to uppercase once, and use that for both.

You don't need to iterate through the whole string, you can stop when you get to the middle.

function palindrome(str) {
  const upper = str.replace(/[^a-zA-Z ]/g, "").toUpperCase()
  for (let i = 0, k = upper.length - 1; i < upper.length/2; i++, k--) {
    if (upper[i] !== upper[k]) {
      return false
    }
  }
  return true;
}

console.log(palindrome("almostomla"));
console.log(palindrome("almotomla"));
console.log(palindrome("almottomla"));

about 4 years ago · Juan Pablo Isaza Report

0

You might want this:

function palindrome(str) {
  const forward = str.replace(/[^a-zA-Z ]/g, "").toUpperCase()
  var n = forward.length
  for (let i = 0; i < n; i++) {
      if (forward[i] !== forward[n-i-1]) {
        return false;
      }
  }
  return true;
}
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!