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

问题描述 投票:3回答:4

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

用例:

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

请帮助。谢谢

javascript regex string
4个回答
4
投票

不需要正则表达式。 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/


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

1
投票

这项工作吗?

if (txtVal[txtVal.length-1]=='%') {
    alert("It's there");
}
else {
    alert("It's not there");
}
© www.soinside.com 2019 - 2024. All rights reserved.