开发者

Regex in javascript always matches only 1 character?

开发者 https://www.devze.com 2022-12-17 02:00 出处:网络
It seems like no matter what input I give this, it always only matches 1 character. m.index is always 0 on a match and m.length is always 1. what am I doing wrong here? I have tried it at(and ripped o

It seems like no matter what input I give this, it always only matches 1 character. m.index is always 0 on a match and m.length is always 1. what am I doing wrong here? I have tried it at(and ripped off some code from) http://www.regular-expressions.info/javascriptexample.html and it works as expected there and matches an entire number.

You can see a live example here http://jsbin.com/aqobe

<html>
<head>
<script type="text/javascript">
function __numberBox__correctFormat(text,allow_float){
    var r;
    if(allow_float){
        r=/\$?[\d,\.\W]+/;
    }else{
        r=/\$?[\d,\W]+/;
    }
    var m=r.exec(text);
    if(m==null){
        return false;
    }
        alert(m.index); alert(m.length);

    if(m.index!=0 || m.length!=text.length){ //must match the whole string
        return false;
    }

    return true;
}
</script>
</head>

<body>
Enter your name: <input type="text" id="fname" onchange="
if(__numberBox__correctFormat(this.value,true)){
  alert('tis true');
}else{
  alert('tis false');
}"  />
</body>

</htm开发者_StackOverflow社区l>

Note I'm wanting for it to accept this input

1234
532,134
$123
493.29


The return value of Regex.exec is always an array containing the list of matches. In your case, the regex will match the whole string so the return value is an array with 1 element that contains the match.

/\$?[\d,\.\W]+/.exec("$493.29")
["$493.29"]


You can use the following code:

var r;
if(allow_float){
    r=/^\$?\d[\d,\.\W]+$/;
} else {
    r = /^\$?\d[\d,\W]+$/;
}

return r.test(text);

EDIT: Reject single $.

The (unescaped) ^ and $ characters match the beginning and of the string, respectively. Therefore, this will only return true if it matches the entire string.

By the way, your regex is very liberal; it matches strings like $1!2@3#4$5%6^7&8*9(0),.1,.4.

I recommend using Javascript's built-in number-parsing methods, like this:

function __numberBox__correctFormat(text,allowFloat){
    if (text.charAt(0) === '$')
        text = text.substring(1);

    return (allowFloat ? parseFloat : parseInt)(text.replace(',', ''), 10);
}

Without the ternary cleverness, that would look like this:

text = text.replace(',', '');
if(allowFloat)
    return parseFloat(text);
return parseInt(text, 10);
0

精彩评论

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