harshalizee
harshalizee

Reputation: 129

Regular Expression regex pattern in javascript for inputs with commas

I have an input scenario where the pattern of input is as follows:

var location = /^[a-z]+\s*[a-z]*,\s*[a-z]+\s*([^,]?[a-z]+)*$/i;

My input are of the following allowed types:

The following input types( the ones with the extra , are not passing the test:

Can anyone tell me what I'm doing wrong here? Any help would be appreciated! Thanks!

And yes, I'm new to regex and js.

Complete code used for testing:

if (str.match(locationstring)){             
console.log("Match pattern str!");          
type = 2;       
}else{          
alert("No match str!");             
return;         
}

Upvotes: 2

Views: 107

Answers (2)

Johannes H.
Johannes H.

Reputation: 6167

Your regexp can only match a , at one position - exactyl where the comma in the regexp is. SO it's obvious that it won'T match strings that include multiple ;)

This regexp will match all your test cases (and, in contrast to yours, match cities that don'T have spaces in their names - those exists, you know? ^^):

/^\w+(\s*\w+)?\s*,\s*\w+\s*(,\s*\w+)?$/i?

(It still does not match contries or states that include whistespace - if it should, tell me.

Upvotes: 1

Bergi
Bergi

Reputation: 664196

var location = /^[a-z]+\s*[a-z]*,\s*[a-z]+\s*([^,]?[a-z]+)*$/i;
                                              ^^^^

Here, you're explicitly disallowing any commata (with a negated character class). Every string that has more than one comma is out with that rule.

It seems you actually want to allow a comma followed by optional whitespace in that place:

var location = /^[a-z]+\s*[a-z]*,\s*[a-z]+(,\s*[a-z]+)*$/i;

Upvotes: 2

Related Questions