javascript - 检查字符串的第一个字符是否为数字会报错,表明 charat 不是有效方法

标签 javascript regex string

我有一个方法可以根据 3 个正则表达式验证字段并根据失败的表达式返回错误。

function mfpValidateValue()
{
    var pCtrl = window.document.forms[0].txtValue;

    var pStrValue  =  mTrim(pCtrl.value);
    if (pStrValue == '')
        return true;

    var regexNum = new RegExp("^[0-9]{9}.{0,3}$"); // First 9 are numeric followed by up to any 3 characters
    var regexLetter1 = new RegExp("^[A-Z]{1,3}[0-9]{6}$"); //Up to the first 3 are alpha, then there are exactly 6 numbers
    var regexLetter2 = new RegExp("^[A-Z]{1,3}[0-9]{9}$"); //Up to the first 3 are alpha, then there are exactly 9 numbers
    var error = "";

    // If any of the RegEx fails, set base error message
    if (!regexNum.test(pStrValue) || !regexLetter1.test(pStrValue) || !regexLetter2.test(pStrValue))
        error = "Please enter a valid Value.";

    // Set more specific error message. 
    if (!isNaN(pStrValue.charat(0)))
        error += " If the first character of Value is a digit, then the first nine characters must be digits.";
    else
        error += " If the first character of Value is a letter, up to the first three characters must be letters proceeded by 6 or 9 digits.";

    return (error == "");
}

我在这一行收到以下错误消息:

    if (!isNaN(pStrValue.charat(0)))

Object doesn't support property or method 'charat'

pStrValue 中的值为:

"12345678"

JavaScript 是否在这里模糊地使用术语“对象”来指代我的特定变量,或者它实际上认为 pStrValue 是一个对象而不是字符串?

最佳答案

你犯了一个小错误。 charat() 不是函数,但 charAt() 是。

你的代码应该是

 if (!isNaN(pStrValue.charAt(0)))

这是函数

http://www.w3schools.com/jsref/jsref_charat.asp

关于javascript - 检查字符串的第一个字符是否为数字会报错,表明 charat 不是有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32103038/

相关文章:

javascript - Laravel 5 通过 laravel :5 query 检查表中是否存在两条记录

javascript - 风 sails 多型号关联

java - 使用正则表达式在 Eclipse 中查找/替换

python - 你如何在 Python 中旋转一个字符串数组?

c++ - 如何将 IF 语句与字符串用户输入一起使用?

javascript - NodeJS 中的嵌套 Promise

javascript - RDF 可以在 MarkLogic 中与 JSON 一起使用吗?

python - 在 Python 正则表达式的 unicode 文本中使用的字边界

regex - Scala列表匹配正则表达式

php - 查找包含非重复特定字母的单词?