3

When given a string such as

address = "12345 White House Lane" 

Is there any way to identify whether the first character of the string ("1" in the example above) is a number or a character? In my case I need to be able to identify if its a number, and if so, shave off the number part of the address (leaving only the street name).

I have tried using the isNaN function

if(isNaN(address[0]){
    //Do this or that
} 

but I am told that it is not reliable enough for broad using. Was also told that I could use a regex function similar to

if(address.matches("[0-9].*")){
    //Do this or that
}

But that only seems to throw type errors that I dont fully understand.

3
  • You can use this /^\d/.test(word) Commented Apr 16, 2018 at 13:58
  • 1
    word.match(/[0-9].*/) <- there is no matches, and you want a regex literal, not a string Commented Apr 16, 2018 at 13:58
  • How is word derived from address? Commented Apr 16, 2018 at 13:58

2 Answers 2

5

You could remove it with a regular expression which looks for starting digits and possible whitespace.

var address = "12345 White House Lane";

address = address.replace(/^\d+\s*/, '');
console.log(address);

Sign up to request clarification or add additional context in comments.

Comments

0

You could split it into the two recognized parts with a function like this:

const splitAddress = address => {
  let {1: number, 2: street} = address.match(/^\s*(\d*)\s*(.+)/)
  return {number, street}
}

console.log(splitAddress('12345 Main St')) //=> {"number": "12345", "street": "Main St"}
console.log(splitAddress('Main St')) //=> {"number": "", "street": "Main St"}
console.log(splitAddress('219 W 48th St')) //=> {"number": "219", "street": "W 48th St"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.