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

205
Views
How to optimize the code? (reverse string)

The task says : Change the order of words in a sentence but let non-alphanumerical characters stay in the same place e.g: 'Hello, it is world here.' -> "here, world is it Hello."

So far i have created something like this, but i need to optimize it (there are too many loops).

var text = 'Hello, it is world here.';

function reverseFunc(text){
  let alpha = text.match(/[a-z0-9]+/gi).reverse();
  let nonAlpha = text.match(/[\W_]+/gi);
  let result = [];
  console.log("Alpha : " + alpha)
  console.log("Non alpha : " +nonAlpha)

 if(alpha == null || nonAlpha == null) console.log(text)
 else if((/[a-z0-9]/i).test(text.split("")[0])){
   if (alpha.length == nonAlpha.length) {
     for (let i = 0; i < nonAlpha.length; i++) {
      result.push(alpha[i], nonAlpha[i]);
     }
     console.log(result.join(""))
     return(result.join(""))
   }else{
     for (let i = 0; i < alpha.length; i++) {
      result.push(alpha[i], nonAlpha[i]);
    }
     console.log(result.join(""))
     return(result.join(""))
   }
 }else{
   if (nonAlpha.length == alpha.length) {
     for (let i = 0; i < alpha.length; i++) {
      result.push(nonAlpha[i], alpha[i]);
     }
     console.log(result.join("")) 
     return(result.join(""))
   }else{
     for (let i = 0; i < nonAlpha.length; i++) {
      result.push(nonAlpha[i], alpha[i]);
    }
     console.log(result.join(""))
     return(result.join(""))
   }
 }
}
reverseFunc(text)

I also have a problem when the text is only 1 char long e.g ".", or " ". I tried this:

if(alpha == null || nonAlpha == null) console.log(text)

but it seems like it is working only for alphanumeric chars.How could this algorithm be corrected?

about 4 years ago · Juan Pablo Isaza
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!