How to use Regular Expression Directly In Javascript
This approach directly employs a regular expression to match numeric and decimal characters in the currency string. It then extracts these characters, joins them to form a numeric string, and converts it to a double value using parseFloat().
// Function to convert currency string to double using regular expression
function convertCurrencyToDouble(currency) {
// Using regular expression to match numeric and decimal characters
const regex = /[\d.]+/g;
// Extracting numeric and decimal characters from the currency string
const matches = currency.match(regex);
// Joining the matched characters to form a numeric string
const numericString = matches.join('');
// Converting the numeric string to a double value
const doubleValue = parseFloat(numericString);
return doubleValue;
}
// Driver code
// Currency in string
let stringCurrency = "$6542.45";
console.log("Currency value: " + stringCurrency);
// Converting currency
let doubleValue = convertCurrencyToDouble(stringCurrency);
// Display currency
console.log("Converted to double: " + doubleValue);
// Currency in string
stringCurrency = "$357,545.45";
console.log("Currency value: " + stringCurrency);
// Converting currency
doubleValue = convertCurrencyToDouble(stringCurrency);
// Display currency
console.log("Converted to double: " + doubleValue);
Output
Currency value: $6542.45 Converted to double: 6542.45 Currency value: $357,545.45 Converted to double: 357545.45
How to convert a currency string to a double value with jQuery or Javascript?
In this article, we will convert a currency string to a double value with jQuery or Javascript. There are two popular ways to convert currency string into float string using different JavaScript inbuilt libraries.
Contact Us