Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!