[英]How to identify if first character in a string is a number in Javascript
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? 有没有办法确定字符串的第一个字符(上例中的“1”)是数字还是字符? 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 我尝试过使用isNaN函数
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"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.