Mar
Mar

Reputation: 1606

How to check first 5 chars & last 5 chars of a string?

I am trying to validate a string only if its first 5 characters are numeric and last 5 characters are letters:

What I have tried:

var userId = "12345abcde";
// Get First and Second Five Characters
var firstFive = userId.substring(0, 5);
var secondFive = userId.substring(5, 10);

// get Global Letter and Nummers
var aStr = /[a-z, A-Z]/g;
var aNum = /[0-9]/g;
var c = userId.match(aNum);

// Try firstFive first...
if (firstFive === c) {
    alert('yes');
} else {
    alert('nop');
} 

This alerts nop.

Is this because firstFive is string and c is object? Where is the error in my thinking?

Live example: http://jsfiddle.net/xe71dd59/1/

Any tips? Thanks in advance!

Upvotes: 0

Views: 1032

Answers (3)

Nadson Luiz
Nadson Luiz

Reputation: 21

Try to do this way:

var userId = "12345abcde";

var result = /^[0-9]{5}.*[a-z]{5}$/i.test(userId);

if (result) {
    alert('yes');
}else{
    alert('nop');
}

Upvotes: 0

James Hunt
James Hunt

Reputation: 2528

match returns an array of results or NULL if none were found.

var c = firstFive.match(aNum);
if(c!=null)
{
    if(c.length==5)
    {
        alert("Yes");
    }
}

Upvotes: 1

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

Try

/^[0-9]{5}.*[a-z]{5}$/i.test("12345abcde")

Upvotes: 7

Related Questions