【问题标题】:javascript check for a special character at the end of a stringjavascript 检查字符串末尾的特殊字符
【发布时间】:2012-01-02 01:43:24
【问题描述】:

我正在从文本字段中获取价值。如果输入的末尾没有出现特殊字符(例如 %),我想显示一条警告消息。

用例:

  1. ab%C - 显示警报
  2. %abc- 显示警报
  3. a%bc- 显示警报
  4. abc%- 好的

到目前为止我想出的正则表达式是这样的。

var txtVal = document.getElementById("sometextField").value;

if (!/^[%]/.test(txtVal))
   alert("% only allowed at the end.");

请帮忙。 谢谢

【问题讨论】:

  • 如果字符串中没有%怎么办?
  • @Sergio Tulentsev。字符串不会有它。它是用户输入的值,其中将包含 %,这意味着用户将输入它 abcde%f 等。
  • 你是说我们可以假设'%'总是存在于字符串中,我们应该检查它是否是最后一个符号?

标签: javascript regex string


【解决方案1】:

不需要正则表达式。 indexOf 将找到一个字符的第一次出现,所以只需检查它是否在末尾:

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

2020年编辑,使用string.endsWith()

【讨论】:

    【解决方案2】:

    你根本不需要正则表达式来检查这个。

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

    http://jsfiddle.net/cwu4S/

    【讨论】:

    • 感谢您的回答,但您的回答似乎不起作用。 jsfiddle.net/4tzmR/1
    • 我在那个例子中有两个语法错误。有一个额外的右括号和一个缺少的分号。 jsfiddle.net/4tzmR/3
    【解决方案3】:
    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.");
    }
    

    【讨论】:

    • 感谢您的回答和帮助,正则表达式似乎有效,但不是第二个。 jsfiddle.net/ZHpDN/2
    • @Nomad,我真傻。修复了第二个。
    【解决方案4】:

    这行得通吗?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-12
      • 1970-01-01
      • 2016-01-14
      • 2011-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多