2

I have a string which is of format 245545g65.

var value = "245545g65"  
var last3Letters = value.substring(7,9);  // abc

Now I want to validate whether the last three letters contains only alphabets, if it is alphabet , i want to alert it.how to alert g?

how do i do this?

Irfan
  • 100
  • 7

5 Answers5

5

assuming that "contains only alphabets" means the last three characters are a combination of the letters a-z:

var str = '245545g65';
if (/[a-z]{3}$/.test(str)){
  // last three characters are any combinations of the letters a-z
  alert('Only letters at the end!');
}
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
0

you can use isNaN to check weather s string is number

if (!isNan(last3Letters))
    alert(last3Letters + ' is number.')
else
    alert(last3Letters + ' is not number.')
sora0419
  • 2,308
  • 9
  • 39
  • 58
  • The non-numeric character may not be in the last 3 characters of the string. – David Starkey Jul 01 '13 at 17:05
  • So if `isNaN()` is `true`, it's a number?? –  Jul 01 '13 at 17:05
  • @David- but he's checking the last 3 characters right?@CrazyTrain - missing !, thanks for pointing that out, I've edited my answer. – sora0419 Jul 01 '13 at 17:08
  • Trouble is that this only guarantees that it can't be converted to a number, not that it has all letters. For example `"q5A"` will fall into the category of "not a number", but it still has a number. OP wants to guarantee 3 letters. –  Jul 01 '13 at 17:11
0

Easy:

var alpha = /^[A-z]+$/;
alpha.test(last3Letters);

This will return a boolean (true/false). Stolen from here.

Community
  • 1
  • 1
PlantTheIdea
  • 16,061
  • 5
  • 35
  • 40
  • How will this work in his example with a g then 2 numbers? Also, this would work with just 1 or 2 letters at the end. – David Starkey Jul 01 '13 at 17:04
  • @DavidStarkey: This answer is testing the last 3 characters, and is anchored to the start and end of that substring. It'll only pass if there are all letters. –  Jul 01 '13 at 17:14
0

you can use RegEx and compare length

var re = new RegExp("[^0-9]*", "g");
var newlast3Letters =last3Letters.replace(re,"");
if(newlast3Letters.length!=last3Letters.length)
{
 alert("not all alphabets");
}
else
{
 alert("all alphabets");
}
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
0

You can also do this:

var value = "245545g65"  
if(value.slice(value.length-3).search(/[^a-z]/) < 0) {
    alert("Just alphabets");
} else {
    alert("Not just alphabets");
}
DarkAjax
  • 15,955
  • 11
  • 53
  • 65