我希望字符串的前两个字符不应该是特殊字符

i want that the first two characters of my string should not be special characters

本文关键字:字符 两个 不应该 特殊字符 字符串 我希望      更新时间:2023-09-26

我希望字符串的前两个字符不应该是特殊字符

function detectInvalidChars(limitField)
{
    var len=limitField.value.length;
    var char1=limitField.value.substring(0,1);
    var char2=limitField.value.substring(1,2);
    if(char1=='&'||char1=='<' char1=='!' || char2=='&'||char2=='<'..........so on)
    {
    alert("Invalid character");
    limitField.value = limitField.value.substring(0,len-1);
    }
}

而不是将char1char2与每个特殊字符匹配。我能做什么?

您可以使用正则表达式:

var re = /^([&<!]|.[&<!])/;
if (re.test(limitField.value)) {
    alert...
}

查看字符串方法 .charCodeAt(n)

然后,您应该能够比较范围内的 ASCII 值。

因此,例如,如果您想排除控件字符,则可以编写类似

if (mystring.charCodeAt(0)<32 || mystring.charCodeAt(1)<32) {
    alert("Invalid character");
}

或使用正则表达式。

您可能会发现这个问题很有帮助:是 JavaScript 的 alpha 替代品?

您可以在原始字符串的子字符串上使用正则表达式。

子字符串获取字符串从"from"到"to"的部分。

/^[0-9a-z]+$/是只允许 0 ...9和...Z

function is_part_alnum(value, from, to) 
    substring = value.substring(from, to);
    if(!substring.match(/^[0-9a-z]+$/) {
        alert("Invalid character(s)");
    }
}

如果你不想使用正则表达式,而是想定义你自己的一组特殊字符,你可以使用这样的函数:

function detectInvalidChars(s, count) {
    var specialChars = "!@#$%^&*()+=-[]'''';,./{}|'":<>?~_";
    var firstChars = s.substr(0, count).split('');
    for(var i=0; i<firstChars.length; i++) {
        if(specialChars.indexOf(firstChars[i]) !== -1) {
            // invalid char detected
        }
    }
}

其中s是字符串,count是应调查的第一个字符的数目。