Reputation: 3616
I have a string which is of format ABC1234567
var value = "ABC1234567"
var first3Letters = value.substring(0,3); // ABC
var next7Letters = value.substring(3,7); //1234567`
Now I want to validate whether variable first3Letters contains only alphabets, and variable next7letters contains only integers.
How do I do this?
Upvotes: 1
Views: 4601
Reputation: 93030
var value = "ABC1234567"
alert("Matches: "+ value.test(/^[A-Za-z]{3}[0-9]{7}$/));
Upvotes: 0
Reputation: 93483
Here's one way:
if ( /^[a-z]+$/i.test (first3Letters ) ) {
// It's good.
}
if ( /^\d+$/.test (next7Letters) ) {
// It's good.
}
Regex explained:
^
specifies the beginning of the string. &
specifies the end of the string.[a-z]
is any word character (A, B, C, etc., but NOT numbers or the the underscore -- which \w
would allow).\d
is any number character (0, 1, 2, etc.)+
means one or more of the previous.i
at the end (i.test
) tells JS to run a case-insensitive search.So the regexes are essentially saying, "From the beginning to the end, are there nothing but 1 or more (word or number) characters."
See also: Regular expressions tutorial.
Upvotes: 3
Reputation: 1845
var test = 'AAAA1122';
chr = test.split(/\d/i);
integer = test.split(/\D/i);
alert("+++++++chr+++++"+chr[0]+"++++++++++++");
alert("++++++int++++++"+integer[0]+"++++++++++++");
Upvotes: 0
Reputation: 6113
For the second you can use the isNaN
method, it'll take a string representation of a number, and return as expected, i.e. var x = 2; var y = "2"
, and both return the same from isNaN()
Upvotes: 0