Home > Enterprise >  How do I let a variable be equal to the regex function of a string
How do I let a variable be equal to the regex function of a string

Time:09-27

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!

CodePudding user response:

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'

CodePudding user response:

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.

  • Related