Skip to content

Instantly share code, notes, and snippets.

@chenten16
Created May 5, 2023 01:07
Show Gist options
  • Save chenten16/98b283a8666ad44a5667b1a43f86b374 to your computer and use it in GitHub Desktop.
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
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