mismas
mismas

Reputation: 1316

Regex to get the currency from price - Typescript

I have this price: $59.95 and I want to get the currency USD $ out of it with the help of RegEx.

This is what I have written so far (I am using Playwright Test and Typescript):

public async getCurrency(): Promise<string | undefined> {
    const price = await this.price.textContent();
    console.log('PRICE');
    console.log(price);
    const currency = price?.replace(/\\d+\\.\\d+/g, '');
    console.log('CURRENCY');
    console.log(currency);
    return currency;
  }

But the currency in the above log file is $59.95 instead of $. The price is as expected - $59.95.
Can you help? What am I doing wrong?

Upvotes: 0

Views: 216

Answers (2)

Cassio Fiuza
Cassio Fiuza

Reputation: 30

you can change your Regex to...

tip: Use trim to remove whitespace from border

const price "$ 88.88"
const currency = price.replace(/\s*\d*[\.|\,]\d*\s*/, "").trim()

Upvotes: 2

mismas
mismas

Reputation: 1316

Silly me, sorry guys! I just had to do this (note no double \):

const currency = price?.replace(/\d+\.\d+/g, '');

Upvotes: 1

Related Questions