检查是否为数字,如果是字母,则在javascript中提取字符串的一部分

Check if numeric,if alphabetic,extract a part of string in javascript

本文关键字:提取 javascript 字符串 一部分 则在 是否 数字 如果 检查      更新时间:2023-09-26

我有那些php脚本:

<input type="text" name="value">
$value=$_POST['value']
if( ctype_alpha(substr($value,0,2)) && is_numeric(substr($value,2,2)) ){
//do smthing
}

我在javascript中找不到类似的验证。我是js的新手,所以我不能独自完成,特别是因为我需要尽快完成它。我需要的是检查输入值的一部分是否仅包含字母字符,输入值的一部分是否仅包含数字字符,当然以及如何提取该部分输入。

使用正则表达式:

/^-?([1-9]'d+|'d)('.'d+)?$/.test("1234"); // true
/^-?([1-9]'d+|'d)('.'d+)?$/.test("asdf"); // false
/^[a-zA-Z]+$/.test("asdf"); // true
/^[a-zA-Z]+$/.test("1234"); // false

或者你只需要两个与PHP同名的函数:

function ctype_alpha(input) {
    // this works for both upper and lower case
    return /^[a-zA-Z]+$/.test(input);
}
function is_numeric(input) {
    // this works for integer, float, negative and positive number
    return /^-?([1-9]'d+|'d)('.'d+)?$/.test(input);
}
ctype_alpha("asdf"); // true
is_numeric("1234"); // true
is_numeric("-1234"); // true
is_numeric("12.34"); // true
is_numeric("0.4"); // true
is_numeric("001"); // false

所以最后是你的代码用法的JS端口:

var input = "your_string"
function ctype_alpha(input) {
    // this works for both upper and lower case
    return /^[a-zA-Z]+$/.test(input);
}
function is_numeric(input) {
    // this works for integer, float, negative and positive number
    return /^-?([1-9]'d+|'d)('.'d+)?$/.test(input);
}
if(ctype_alpha(input.substring(0, 2)) && is_numeric(input.substring(2, 4))) {
    //do smthing
}