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
Getting the content between two characters

So I have this (example) string: 1234VAR239582358X

And I want to get what's in between VAR and X. I can easily replace it using .replace(/VAR.*X/, "replacement"); But, how would I get the /VAR.*X/as a variable?

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

0

I think what you are looking for might be

string.match(/VAR(.*)X/)[1] 

The brackets around the .* mark a group. Those groups are returned inside the Array that match creates :)

If you want to only replace what's in between "VAR" and "X" it would be

string.replace(/VAR(.*)X/, "VAR" + "replacement" + "X");

Or more generic:

string.replace(/(VAR).*(X)/, "$1replacement$2");
about 4 years ago · Juan Pablo Isaza Relatório

0

If you

want to get what's in between VAR and X

then using .* would do the job for the given example string.

But note that is will match until the end of the string, and then backtrack to the first occurrence of X it can match, being the last occurrence of the X char in the string and possible match too much.

If you want to match only the digits, you can match 1+ digits in a capture group using VAR(\d+)X

const regex = /VAR(\d+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);

if (m) {
  let myVariable = m[1];
  console.log(myVariable);
}

Or you can match until the first occurrence of an X char using a negated character class VAR([^\r\nX]+)X

const regex = /VAR([^\r\nX]+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);

if (m) {
  let myVariable = m[1];
  console.log(myVariable);
}

about 4 years ago · Juan Pablo Isaza Relatório

0

You can store it as variable like this,

const pattern = "VAR.*X";
const reg = new RegExp(pattern);

Then use,

.replace(reg, "replacement");
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