自动删除新字符 JavaScript
auto delete new characters javascript
我正在为学校做一个实验室,目标是创建一个 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 位数字
$/字符串的必填结尾
相关文章:
- 使用JSON.parse时出现无效字符javascript错误
- 使用特殊字符 Javascript 对 URL 进行编码
- 如何替换不可打印的unicode字符(Javascript)
- 正则表达式密码允许特殊字符 JavaScript
- 正则表达式不允许特殊字符(Javascript)
- 如何删除字段中的字符 javascript
- 自动删除新字符 JavaScript
- 按下退格键时删除一组字符(Javascript)
- 获取某些字符 JavaScript 的所有可能组合
- 如何获取有关输入名称长度的字符 - javascript 的警报
- 当前字符JavaScript的RegExp
- 不允许使用除允许使用的字符javascript regex之外的特殊字符
- Regex,只允许一组特定的字符(Javascript)
- 缺少空白后的字符-javascript
- 输入只允许英文和非英文字符javascript
- 如何检查字符串是否有起始字符是特殊字符:javascript
- 正则表达式(regex): /W带连字符(javascript)
- 测试特殊字符JavaScript
- 密码-大写字符JavaScript
- 如何提取类型数字的最后字符javascript/jquery