简体   繁体   中英

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

I have those php scripts:

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

I cannnot find a similar validation in javascript.Im new to js so i cant do it alone,especially because i need it as fast as possible. What i need is to check if a part of an input value contains only alphabetic characters,if a part of an input value contains only numeric characters, and of course how to extract that part of an input.

Use regular expression:

/^-?([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

Or you just want two functions with the same name as 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

So finally a port to JS of your code usage:

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
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM