开发者

Identifying string format in Javascript

I'm trying to solve a (simple) programming problem in Javascript and I can't figure out how to get it working. I have a program which starts by reading in a text string usi开发者_如何学JAVAng prompt.

The program outputs either "Valid name" or "Invalid name", depending on whether the input names fit the required format, which is:

"last name, first name, middle initial"

where neither of the names can have more than 15 characters.

I know there's an easy way to do this, but I can't seem to find it anywhere. Thanks for your help!


I wouldn't use \w, as it includes characters such as _ and the nine digits. Consider the regular expression in the following test:

<script>
    if ("Nami, Guilherme, P".match(/^[A-Z][a-z]{1,14}, [A-Z][a-z]{1,14}, [A-Z]\.?$/)) {
        alert("Valid");
    }
    else {
        alert("Invalid");
    }
</script>


use this regular expression:

/^\w{0,15}, \w{0,15}, \w{0,15}\.?$/.test(name)


This should work (worked in my testing):

// assuming there are no commas in fields
var string = "last name, first name, middle initial", 
string_array = string.split(', '), 
length = string_array.length;

for (i = 0; i < length; i++) {
    // changing string to 'blah, firrrrrsssttt nammme, bbbbb' outputs the alert message
    if (string_array[i].length > 15) alert('None of these can be more than 15 characters long. ' + string_array[i] + ' is too long');
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜