-2

Hi i am trying to change the following regex:

const usdRate = /(currency="USD" rate="(.*?)("))/.exec(line)[2]

For each cicle i want to change USD to EUR, JPY and so on.

example:

line has an xml line loaded into it.

const array = ['USD, 'EUR', 'JPY'];

for(let i=0, i<=2; i++){
 
    console.log(/(currency="+array[i]+" rate="(.*?)("))/.exec(line)[2]);

}

I tried many ways to send the current text in a array i want into the regex expression but nothing works. Do you know how can i change the regex expression in a for cicle on each iteraction?

user ct
  • 47
  • 6

1 Answers1

-1

To create a regexp dynamically you need to use the new RegExp() constructor with a string argument.

const array = ['USD, 'EUR', 'JPY'];

for(let i=0, i<=2; i++){
    let re = new RegExp(`(currency="${array[i]}" rate="(.*?)("))`)
    console.log(re.exec(line)[2]);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612