ThisIsMe
ThisIsMe

Reputation: 325

Javascript regex: match an adress (number + name of the street)

I would like to use a regex in Javascript to match to a string that contains a number in 1st position then a street name, for instance:

54 street Saint-Louis

The regex I tried is like this: var res = /[0-9]\s[A-Z]\s[A-Z-]/.test("8 street Saint-Louis");

But it returns false...

Any idea?

Upvotes: 1

Views: 312

Answers (1)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

issues :

[A-Z] : it will only match a single alphabet so use either * or +

your sample case include lowercase letters but your regex is only looking for uppercase so use [a-zA-Z]

so use ^\d+\s[a-zA-Z]+(\s[a-zA-Z-]*)?$

^\d+ : starts with one or more digits

\s[a-zA-Z]+ : space then one or more alphabets

(\s[a-zA-Z-]*)? : ? zero or one match of ,space and zero or more alphabets and - , $ mean end of string match

Demo

console.log(/^\d+\s[a-zA-Z]+(\s[a-zA-Z-]*)?$/.test('8 street Saint-Louis')); 
console.log(/^\d+\s[a-zA-Z]+(\s[a-zA-Z-]*)?$/.test('8 street')); 
console.log(/^\d+\s[a-zA-Z]+(\s[a-zA-Z-]*)?$/.test('8748 street Saint-Louis')); 
//-----------------------------------------------------------

console.log(/^\d{1,3}\s[a-zA-Z]+(\s[a-zA-Z-]*)?$/.test('8748 street Saint-Louis')); 

Upvotes: 1

Related Questions