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

206
Visualizações
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
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