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

186
Visualizações
new RegExp doesnt seem to work the same as without

A brief explanation: I have a string which contains sentences. I want to change a specific word to Foo+word+Bar For example the word that i want to change in this case is "this". "this" should only be changed when it stands alone for example:

HellothisOk, HelloThis thisthis and ThisOk

should not be changed, while:

thiS, "this" this!!! this %this!? this? this. THIS

Should change.

The code below works perfect (from this answer):

const str = 'Hello This is a test string this is a test THISthis is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible. this??? this! "this "this" this" HellothisOk HelloThis ThisOk';

const result = str.replace(/(?<!\w)(this)(?!\w)/gi, "Foo$1Bar");

console.log(result)

But when want to change "this" to a variable like this:

const str = 'Hello This is a test string this is a test THISthis is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible. this??? this! "this "this" this" HellothisOk HelloThis ThisOk';

const variable = "this";

const result = str.replace(new RegExp('(?<!\w)('+variable+')(?!\w)', 'gi'), "Foo$1Bar");

console.log(result);

I don't get the same output and I don't understand why.

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

0

You don't need to append and prepend / when putting a RegExp in a string. Also make sure to escape any backslashes.

const str = 'Hello This is a test string this is a test THISthis is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible. this??? this! "this "this" this" HellothisOk HelloThis ThisOk';

const variable = "this";

const result = str.replace(new RegExp('(?<!\\w)('+variable+')(?!\\w)', 'gi'), "Foo$1Bar");

console.log(result);

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