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

343
Visualizações
How to replace words in string by regex pattern with exception

There is a regex pattern:

[a-zA-Z0-9]+.?(com|net)

I use it to replace the words in strings with this function:

const formatString = (str) => {
   const regex = new RegExp("[a-zA-Z0-9]+.?(com|net)","gi");
   return str.replace(regex, "*")
}

function execution examples:

formatString("google.com something else.net") // returns: "* something *"
formatString("google.com") // returns: "*"
formatString("something") // returns: "something"

but in some cases, I need to make an exception word so that it is not replaced.

Example:

exception word is google (or google.com)

formatString("google.com something else.net") // should returns: "google.com something *"

I tried to do it with negative lookahead using this pattern: (?!google)[a-zA-Z0-9]+.?(com|net), but it does not work, it only ignores the first letter of the word.

Match information from https://regex101.com/

match information from regex101 dot com

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use

const regex = /\b(?!google\b)[a-zA-Z0-9]+\.(?:com|net)\b/gi;

Details:

  • \b - word boundary
  • (?!google\b) - a negative lookahead that fails the match if there is google as a whole word immediately to the right of the current position
  • [a-zA-Z0-9]+ - one or more ASCII letters or digits
  • \. - a dot
  • (?:com|net) - a non-capturing group matching either com or net
  • \b - a wor boundary.
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