自动删除新字符 JavaScript

auto delete new characters javascript

本文关键字:字符 JavaScript 删除 新字符      更新时间:2023-09-26

我正在为学校做一个实验室,目标是创建一个 Web 控件,只接受用户的货币值。

Rules:
1st digit must be “-“ or “$”
2nd digit must be “$” or a number
3rd digit on must be a number or a “.”
Only two digits after decimal
Must have a “$”

我遇到的问题是,虽然我可以设置标签以在允许或不允许某些内容时显示,但我无法弄清楚如何在不满足条件时让它自动删除新字符。(例如,不能输入"-1",只能输入"-$"或"$1"。尝试设置子字符串的长度似乎不起作用。当前示例中的条件似乎也仅在字符串仅包含"-"时才有效。添加的任何额外字符都不会触发它。

法典:

    function text2money(e) {
        // get value of txt
        var str = document.getElementById("<%=txt.ClientID %>").value;
        if (str.substring(0, str.length) === "-" && str.substring(1, str.length) !== "$") {
                str.length = 2;
        }
        // goes through string one character at a time, converts them to char, then checks if char is a decimal digit
        if (str.substring(0, 1) === ('-') || str.substring(0, 1) === ('$')) {
            document.getElementById("<%= lbl1.ClientID %>").innerHTML = "True"; // must use .innerHTML with labels
            // check if second digit is '$' or numeric
            if (str.substring(1, 2) === ("$") || isFinite(str.substring(1, 2))) {
                document.getElementById("<%= lbl1.ClientID %>").innerHTML = "It's numeric";
                // check if third and any future characters are '.' or numeric
            } // end second char if
            else {
                document.getElementById("<%= lbl1.ClientID %>").innerHTML = "Second char must be '$' or numeric";
            } // end second char
        } // end first char if
        else {
            document.getElementById("<%= lbl1.ClientID %>").innerHTML = "First character must be '-' or '$'";
        } // end first char
        // check if $ is included anywhere in the string
        var result = str.indexOf("$") <= -1; // -1 == false
        if (result) {
            document.getElementById("<%= lbl2.ClientID %>").innerHTML = "$ is a required character";
            }
            else {
                document.getElementById("<%= lbl2.ClientID %>").innerHTML = "";
            }
        } // end text2money

使用正则表达式对象:

        (/^-?'$'d+'.'d{2}$/).test(inputString)

/^ 将模式的开头定义为字符串的开头

-? 1 个可选 -

''$ 1 强制性 $

''d+ 1 位或更多位数字

. 强制。

''d{2}正好 2 位数字

$/字符串的必填结尾