javascript检查字符串末尾的特殊字符

时间:2012-01-02 01:43:25

标签: javascript regex string

我从文本字段中获取价值。如果有特殊字符,我想显示一条警告信息,比如输入输入结尾没有出现%。

Usecases:

  1. ab%C - 显示提醒
  2. %abc- show alert
  3. a%bc- show alert
  4. abc% - ok
  5. 到目前为止我出现的正则表达式就是这个。

    var txtVal = document.getElementById("sometextField").value;
    
    if (!/^[%]/.test(txtVal))
       alert("% only allowed at the end.");
    

    请帮忙。 感谢

4 个答案:

答案 0 :(得分:3)

不需要正则表达式。 indexOf会找到第一个出现的字符,所以只需在最后检查它:

if(str.indexOf('%') != str.length -1) {
  // alert something
}

答案 1 :(得分:2)

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.");
}

答案 2 :(得分:2)

您根本不需要正则表达式来检查这一点。

var foo = "abcd%ef";
var lastchar = foo[foo.length - 1];
if (lastchar != '%') {
    alert("hello");
}

http://jsfiddle.net/cwu4S/

答案 3 :(得分:1)

这会有用吗?

if (txtVal[txtVal.length-1]=='%') {
    alert("It's there");
}
else {
    alert("It's not there");
}
相关问题