简体   繁体   中英

javascript for checking alphabets from a string

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?

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

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!');
}

you can use isNaN to check weather s string is number

if (!isNan(last3Letters))
    alert(last3Letters + ' is number.')
else
    alert(last3Letters + ' is not number.')

Easy:

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM