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

120
Visualizações
Function that replaces the wrapped word with ampersands with just single hashtag at start

I tried to write a function to replace ampersands which are arround word in string with just single hashtag which will be at the beginning of word &word& => #word. And I did it, but after looking at my code I can tell that it's kind of ugly, and also I need function that will return text to version with ampersands too. So, maybe someone can tell me how can I improve it? Maybe someone can provide version with regex?

const text = "&string& someText&string2& &string3& &string4&&string5&";

const replaceAmpersandsWithHashtag = (text: string) => {
    const firstStep = text.replace(/\&/g, '#');
    let occurenceOfHashtag = 0;
    const secondStep = firstStep.split('').filter(char => {
      if(char === '#') {
        occurenceOfHashtag += 1 ;
        return occurenceOfHashtag % 2 === 0 ? false : true;
      }
      return true
      }).join('');
    return secondStep
}

const replaceHashtagWithAmpersands = (text: string) => {
    const firstStep = text.replace(/\#/g, '&');
    let isLookingForNextAmpersand = false;
    const secondStep = firstStep.split('').map((char, index) => {
      if(char === '&') {
        isLookingForNextAmpersand = true;
        return char;
      }
      if(isLookingForNextAmpersand && firstStep.length === index + 1) {
        isLookingForNextAmpersand = false;
        return `${char}&`
      }
      if(isLookingForNextAmpersand && (firstStep.charAt(index + 1) === ' ' || firstStep.charAt(index + 1) === '&')) {
        isLookingForNextAmpersand = false;
        return `${char}&`
      }
      return char
      }).join('');
    return secondStep
}

const textWithHastags = replaceAmpersandsWithHashtag(text);
const againWithAmpersands = replaceHashtagWithAmpersands(textWithHastags);

// Should be "#string someText#string2 #string3 #string4#string5"
console.log(textWithHastags)
// Should be "&string& someText&string2& &string3& &string4&&string5&"
console.log(againWithAmpersands)
// Should be "true"
console.log(text === againWithAmpersands)
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Use a capture group in the regexp to copy the word between the & to the replacement.

function replaceAmpersandsWithHashtag(string) {
  return string.replace(/&(\w+)&/g, '#$1');
}

function replaceHashtagWithAmpersands(string) {
  return string.replace(/#(\w+)/g, '&$1&');
}

const text = "&string& someText&string2& &string3& &string4&&string5&";

const textWithHastags = replaceAmpersandsWithHashtag(text);
const againWithAmpersands = replaceHashtagWithAmpersands(textWithHastags);

// Should be "#string someText#string2 #string3 #string4#string5"
console.log(textWithHastags)
// Should be "&string& someText&string2& &string3& &string4&&string5&"
console.log(againWithAmpersands)
// Should be "true"
console.log(text === againWithAmpersands)

about 4 years ago · Juan Pablo Isaza Relatório

0

you are overkilling the solution, you can do it easily with the function replaceAll which will replace the occurrences of your search, in this case you will need to use some regex in order to do a proper replacement, so you can use &(\w+)& where the (\w+) part will capture the group between the & and then you can use it in the replace call as $1.

here is your code with the implementation of the explanation above

const text = "&string& someText&string2& &string3& &string4&&string5&";

const replaceAmpersandsWithHashtag = (text) => {
    return text.replaceAll(/&(\w+)&/g, '#$1');
}

const replaceHashtagWithAmpersands = (text) => {
    return text.replaceAll(/#(\w+)/g, '&$1&');
}

const textWithHastags = replaceAmpersandsWithHashtag(text);
const againWithAmpersands = replaceHashtagWithAmpersands(textWithHastags);

// Should be "#string someText#string2 #string3 #string4#string5"
console.log(textWithHastags)
// Should be "&string& someText&string2& &string3& &string4&&string5&"
console.log(againWithAmpersands)
// Should be "true"
console.log(text === againWithAmpersands)

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