Created
May 5, 2023 01:07
-
-
Save chenten16/98b283a8666ad44a5667b1a43f86b374 to your computer and use it in GitHub Desktop.
A js function to extract currency symbols and amounts from a given input string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const extractCurrencyAndPrice = fullPrice => { | |
// Regular expression to match currency symbol and amount | |
const regex = /((?:\p{Sc}|[a-zA-Z]{1,3})\s*)?([\d,.]+)(?:\s*((?:\p{Sc}|[a-zA-Z]{1,3})))?/gu; | |
const matches = regex.exec(fullPrice); | |
if (!matches) { | |
throw new Error('Invalid input format [input: ' + fullPrice + ']'); | |
} | |
const currency = matches[1] || matches[3]; | |
const amount = parseFloat(matches[2].replace(',', '.')); | |
return { currency, amount }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment