Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading