4

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

3
  • What if % is not present in the string? 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
    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? Jan 2, 2012 at 1:49

4 Answers 4

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()

0
2

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.net/cwu4S/

2
  • thanks for your answer, but your answer doesn't seem to be work. jsfiddle.net/4tzmR/1
    – Nomad
    Jan 2, 2012 at 2:01
  • I had two syntax errors in that example. There was an extra closing parenthesis and a missing semicolon. jsfiddle.net/4tzmR/3
    – mrtsherman
    Jan 2, 2012 at 2:07
2
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.");
}
2
  • Thanks for your answer and help, the regex one seems to be work but not the 2nd one. jsfiddle.net/ZHpDN/2
    – Nomad
    Jan 2, 2012 at 1:57
  • @Nomad, That was dumb of me. Fixed the 2nd. Jan 2, 2012 at 15:58
1

Would this work?

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.