Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript check for a special character at the end of a string

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

like image 438
Nomad Avatar asked Dec 27 '22 08:12

Nomad


1 Answers

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

like image 118
Andy Ray Avatar answered Dec 30 '22 10:12

Andy Ray