1

Hey Folks I'm trying to extract the amount from a variable that looks something like this.

var amountStr  = "iPhone ($45.00)";

I've tried the following code to extract it

var amountNum= amountStr.replace( /^\D+/g, '');

how ever the output is as follows

45.00)

Could someone let me know how I should go about dropping the last ')' in a cleaner way?

Thank you.

2 Answers 2

3

You have a "beginning of text" marker in your regex. This is why it doesn't match the dot, or the parenthesis.

var amountNum= amountStr.replace( /\D+/g, '');

will replace all non-digits in a string. However you need your dot in place, thus this should be used:

var amountNum= amountStr.replace( /[^\d\.]+/g, '');

Next, to make sure that you actually have a number (not a string), so you can perform correct adding, use this:

var amountNum = parseFloat(amountStr.replace( /[^\d\.]+/g, ''));

But, in case you have strings like "iPhone3 ($45.00)", the result will be 345, instead of 45. You need to find exactly what you need in this string, instead of looking for what you don't need. An example would be this:

var amountNum = parseFloat(amountStr.match( /\d+(\.\d+)?/g)[0]);

This will also not work with "iPhone3", but at least you won't have 345, but just 3.

So just look for the last number, like this:

var amountNum = parseFloat(amountStr.match( /\d+(\.\d+)?/g).pop());
Sign up to request clarification or add additional context in comments.

2 Comments

Ah perfect! Thank you so much for the explanations as well. Cheers.
To avoid the problem with "iPhone3" you could do something like this. parseFloat(amountStr.match(/\$[\d\.]+/g).pop().slice(1)); The \$ at the start will match the string including and after the $ and the numbers. Then pop will get the first match, and slice(1) will get you the number after the $. Then parseFloat will turn it into a float.
0

Use substring method and specify the indices of the amount between both the brackets (which can be found out by having the indices of brackets)

var amountStr  = "iPhone ($45.00)";
var n1 = amountStr.indexOf("(");
var n2 = amountStr.indexOf(")");    
var amountNum= amountStr.substring(n1+2, n2)  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.