0

I'm running the following javascript in a Chrome. It's yielding a blank string when I'm expecting "123456.78".

var amt = "$123,456.78";
digitRegex = /(\d|\.)*/
amtarr = digitRegex.exec(amt);
amtstr = amtarr.join("");
alert(amtstr);

Any ideas?


FINAL CODE ENDED UP BEING THIS:

 moneyRegex = /^\$?(\d{1,3}(\,\d{3})*|(\d+))(\.\d{1,2})?$/
    amt = $("#txtAmt").val();
    amtok = (amt.search(moneyRegex) != -1);
    amtval = 0;
    if (amtok == true) {
         digitRegex = /[\d\.]+/g
         amtarr = digitRegex.exec(amt);
         amtstr = amtarr.join("");
         alert(amtstr);
    }

3 Answers 3

3
amtstr = amt.replace(/[$,]/g, "");

will give you what you want. It removes the commas and the dollar sign from your string, leaving 123456.78.

Sign up to request clarification or add additional context in comments.

2 Comments

Or, depending on the context, you might consider amt.replace ( /[^\d.]/g, '') which will remove all characters which are not digits or '.'
+1 Thanks @Tim, wish I could check both your answer and sergio.
1

You could try with

digitRegex = /(\d|\.)*/g

to get all the matches. You could also use:

digitRegex = /[\d\.]+/g

which should be ok for what you are trying to do.

1 Comment

Thanks @sergio, that did it. Missing the global flag was the trick.
0

I am not sure why * doesn't return a result, change it to + and it will work.

But there is another bug in your code.

digitRegex.exec(amt);

returns an array, but it contains only the first match and the position of the next and some other stuff. See here mozilla.org

You have to call exec until it returns null to get all matches and only the first item in the array contains your match.

var amt = "$123,456.78";
digitRegex = /(\d|\.)+/g;
var result = new Array();
while ((amtarr = digitRegex.exec(amt)) != null)
{
result.push(amtarr[0]);
}

amtstr = result.join("");
alert(amtstr);

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.