JAB
JAB

Reputation: 3616

Test strings for all alphabet characters or all integers

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

Answers (4)

Petar Ivanov
Petar Ivanov

Reputation: 93030

var value = "ABC1234567"  

alert("Matches: "+ value.test(/^[A-Za-z]{3}[0-9]{7}$/));

Upvotes: 0

Brock Adams
Brock Adams

Reputation: 93483

Here's one way:

if ( /^[a-z]+$/i.test (first3Letters ) ) {
    // It's good.
}

if ( /^\d+$/.test (next7Letters) ) {
    // It's good.
}

See it in action at jsFiddle.


Regex explained:

  1. ^ specifies the beginning of the string.
  2. & specifies the end of the string.
  3. [a-z] is any word character (A, B, C, etc., but NOT numbers or the the underscore -- which \w would allow).
  4. \d is any number character (0, 1, 2, etc.)
  5. + means one or more of the previous.
  6. The 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

K6t
K6t

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

Psytronic
Psytronic

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

Related Questions