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

138
Visualizações
How do I let a variable be equal to the regex function of a string

to clarify I'm using React and Material UI. I have strings in the format of : CAD - Canadian Dollar and I would like to use regex to create a string that would be equivalent to Canadian Dollar. Essentially the everything before the - would need to removed, and the one blank space in front of it would need to be removed as well. Following that I would like to set some variable to be equal to that returning string.

Here is my attempt:

const userCurrency = 'USD - United States Dollar'

const varSetter = (e) => {
        var test1 = e.target.innerText;
        setUserCurrency(test1);
        console.log(userCurrency);

        const currencyRegex = userCurrency.match(/[^-]*$/g)


        console.log(currencyRegex);
      }

This returns an array [' United States Dollar', ''] but how do I remove the leading whitespace, and have the result as a string and not an array? Thank you!

almost 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Use the replace() function to remove the match of the pattern.

const currencyRegex = userCurrency.replace(/.*\s+-\s+/, '');

This regexp matches everything up to the last -. It also requires whitespace around the -, and removes the whitespace after it as well.

almost 4 years ago · Santiago Trujillo Relatório

0

There's a few ways you could handle this... if all of the strings have the same pattern of [prefix] - [currency name] then you could change your RegEx to use a lookbehind, and combine this with array destructuring:

const [currency] = 'USD - United States Dollar'.match(/(?<=-\s).+/)

console.log(currency);  // 'United States Dollar'

However, do you really need a regular expression? If it's always a three character prefix, then substring is fit for purpose:

const currency = 'USD - United States Dollar'.substring(6);

console.log(currency);  // 'United States Dollar'
almost 4 years ago · Santiago Trujillo 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