最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - javascript check for a special character at the end of a string - Stack Overflow

programmeradmin4浏览0评论

I am getting value from a text field. I want to show an alert message if a special character, say % doesn't appear at the end of entered input.

Usecases:

  1. ab%C - show alert
  2. %abc- show alert
  3. a%bc- show alert
  4. abc%- ok

The regex i came up so far is this.

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

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

Please help. Thanks

I am getting value from a text field. I want to show an alert message if a special character, say % doesn't appear at the end of entered input.

Usecases:

  1. ab%C - show alert
  2. %abc- show alert
  3. a%bc- show alert
  4. abc%- ok

The regex i came up so far is this.

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

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

Please help. Thanks

Share Improve this question edited Jan 2, 2012 at 1:44 Nomad asked Jan 2, 2012 at 1:43 NomadNomad 1,10012 gold badges29 silver badges42 bronze badges 3
  • What if % is not present in the string? – Sergio Tulentsev Commented Jan 2, 2012 at 1:45
  • @Sergio Tulentsev. The string wont have it. It's user entered value which will contain the %, meaning user will enter it abcde%f etc. – Nomad Commented Jan 2, 2012 at 1:47
  • are you saying that we can assume that '%' always exists in the string, and we should check if it's the last symbol or not? – Sergio Tulentsev Commented Jan 2, 2012 at 1:49
Add a ment  | 

4 Answers 4

Reset to default 5

No need for a regex. indexOf will find the first occurrence of a character, so just check it it's at the end:

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

2020 edit, use string.endsWith()

You don't need regex to check for this at all.

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

http://jsfiddle/cwu4S/

if (/%(?!$)/.test(txtVal))
  alert("% only allowed at the end.");

or to make it more readable by not using a RegExp:

var pct = txtVal.indexOf('%');
if (0 <= pct && pct < txtVal.length - 1) {
  alert("% only allowed at the end.");
}

Would this work?

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

评论列表(0)

  1. 暂无评论