Pradeep
Pradeep

Reputation: 99

Why doesnt this Javascript regular expression work

var existing = "";   
if(disk.isLinux){   
    var valinvalid = "/usr" ;            
    var valinput = /^\/[a-zA-Z]{2,}/ ;  
    if(!valinput.match(valinvalid)){      
        return "^/" + existing + "[^/][a-zA-Z]{2,}[^/]$";
    } 
}

Here im trying to do the following in the first if condition ie. if(disk.isLinux):
1. there should be minimum 3 characters
2. the first character should be /
3. the entire input shouldnt match "/usr". But it can be /us or /usra

Upvotes: 0

Views: 94

Answers (3)

Vikram
Vikram

Reputation: 8333

try changing your code to use:

var valinput = new RegExp("/^\/[a-zA-Z]{2,}/") ;  
 if(!valinput.test(valinvalid)){

Upvotes: 0

nana
nana

Reputation: 4491

If you are just trying to test if it matches, us test on regexp:

/^\/[\w]{2,}/.test("/usr/");     //true

Is this what you are trying to do?

Upvotes: 1

Roderick Obrist
Roderick Obrist

Reputation: 3828

A couple of things:

1) vars should never ever ever be inside if statements

2) String.prototype.match exists RegExp.prototype.match does not

But more importantly, you dont need regEx at all

if (
 input.length < 3 ||
 input.charAt(0) !== '/' ||
 input === '/user'
) {
 throw new Error("I'm not happy with the input");
}

Upvotes: 0

Related Questions