开发者

Javascript Regex Exec not Matching

开发者 https://www.devze.com 2023-03-23 09:17 出处:网络
I\'m running the following javascript in a Chrome.It\'s yielding a blank string when I\'m e开发者_运维百科xpecting \"123456.78\".

I'm running the following javascript in a Chrome. It's yielding a blank string when I'm e开发者_运维百科xpecting "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);
    }


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

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


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.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消