如何区分 Javascript 中的 id(数字)和 email(字符串)?
How can I difference id (number) and email (string) in Javascript?
我有 API,其中一些 return 只能发送电子邮件,有些 return 只能发送 ID。例如:
用户1
value: example@example.com
用户 2
value: 1212391361783212
如果我有输入并且想给出值(如果值为 email
),我需要它。如果值为id
,则输入值必须为null
<input value={???}/>
您可以使用 isNaN 检查字符串是否为有效数字。所以
if(isNaN(value)) {
// value is email
} else {
// value is id
}
您的代码示例不完整,但您尝试执行的操作应如下所示。与其假设任何 non-numerical 回复都是有效的电子邮件(将来可能会随着 API 的变化而中断),不如如下所示明确说明您要查找的内容。
// Assume you're comfortable using a relatively loose pattern to match an email i.e. no overly strict formatting rules
const mailPattern = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
// Assume response is in scope and contains the API response with the email or id deserialized from the body
const value = mailPattern.test(response) ? value : null
您可以使用 Regular expression /^\d+$/
combined with RegExp.prototype.test():
if (/^\d+$/.test(value)) {
// It's number
}
我有 API,其中一些 return 只能发送电子邮件,有些 return 只能发送 ID。例如:
用户1
value: example@example.com
用户 2
value: 1212391361783212
如果我有输入并且想给出值(如果值为 email
),我需要它。如果值为id
,则输入值必须为null
<input value={???}/>
您可以使用 isNaN 检查字符串是否为有效数字。所以
if(isNaN(value)) {
// value is email
} else {
// value is id
}
您的代码示例不完整,但您尝试执行的操作应如下所示。与其假设任何 non-numerical 回复都是有效的电子邮件(将来可能会随着 API 的变化而中断),不如如下所示明确说明您要查找的内容。
// Assume you're comfortable using a relatively loose pattern to match an email i.e. no overly strict formatting rules
const mailPattern = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
// Assume response is in scope and contains the API response with the email or id deserialized from the body
const value = mailPattern.test(response) ? value : null
您可以使用 Regular expression /^\d+$/
combined with RegExp.prototype.test():
if (/^\d+$/.test(value)) {
// It's number
}