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.
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);
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"}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.