我正在从文本字段中获得价值。如果要输入的输入末尾没有特殊字符(例如%),我想显示一条警报消息。
用例:
到目前为止我提出的正则表达式是这个。
var txtVal = document.getElementById("sometextField").value;
if (!/^[%]/.test(txtVal))
alert("% only allowed at the end.");
请帮助。谢谢
不需要正则表达式。 indexOf将找到一个字符的第一个匹配项,因此只需检查它是否在末尾即可:
if(str.indexOf('%') != str.length -1) {
// alert something
}
2020编辑,使用string.endsWith()
您完全不需要正则表达式来检查它。
var foo = "abcd%ef";
var lastchar = foo[foo.length - 1];
if (lastchar != '%') {
alert("hello");
}
if (/%(?!$)/.test(txtVal))
alert("% only allowed at the end.");
或通过不使用RegExp
使其更具可读性:
var pct = txtVal.indexOf('%');
if (0 <= pct && pct < txtVal.length - 1) {
alert("% only allowed at the end.");
}
这项工作吗?
if (txtVal[txtVal.length-1]=='%') {
alert("It's there");
}
else {
alert("It's not there");
}