mike
mike

Reputation: 47

How to define a regular expression to extract currency symbol from price string?

I have a price string from which I want to get the currency symbol (symbol has variable length).

The price can be presented in different formats. I am removing the points, commas and digits but sometimes a comma or point is shown before the currency symbol

var k = "111,112,258$".replace(/\d+([,.]\d+)?/g, "");
console.log(k) //log shows ,$

I think the second comma or point is the problem. Why is this happening?

Upvotes: 3

Views: 1419

Answers (2)

Nir Alfasi
Nir Alfasi

Reputation: 53525

You can simplify the regex and replace only the characters you're interested in without mentioning the others:

"111,112,258$".replace(/[\d,.]/g, "")

output (screenshot done from node terminal):

enter image description here

Upvotes: 2

Mohamed Shaaban
Mohamed Shaaban

Reputation: 1169

This replaces digits, commas, dots, and spaces from your input string

var k = "111,112.111$".replace(/[\d,.\s]/g, "");
console.log(k) // $

EDIT:

If you want to support Arabic/Indian numbers, you could extend it further like

var k = "١٢٣,١١$".replace(/[\d,.\s,١-٩]/g, "");
console.log(k) // $

Upvotes: 4

Related Questions