繁体   English   中英

Javascript的search()函数无法正常运行

[英]search() function of Javascript does not behave properly

我不知道为什么search()函数对于带有SPECIAL CHARACTER的任何输入都返回0,我想查找第一个出现特殊字符的位置。 当我对search()方法的值进行硬编码时,它工作正常,但是当我从文本框中获取值时,它无法正常工作。

以下是我的HTML代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<script type="text/javascript" src="jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="test.js"></script>

</head>
<body>

    <input type="text" id="txt" onkeyup="return checkLength();"/>
    <input type="button" id="btn" value="Verify" onclick="getValue()"/>


</body>
</html>

以下是我实现了使用Javascript的search()的脚本,但不知道为什么我的任何输入都得到0值。 实际上,我想找到第一个特殊字符出现的位置。

$(document).ready(function() {

    $('#btn').attr('disabled',true);

    $("#txt").bind({
        paste : function(){
            $('#btn').attr('disabled',false);
            checkLength();
        },
        cut : function(){
            checkLength();
        }
    });
});

function checkLength(){

    var txtLength = $("#txt").val().length;
    var banTxt = document.getElementById("txt").value;

    if (txtLength != 0) {

        if(isAlphaNumeric(document.getElementById("txt").value)) {
            $('#btn').attr('disabled',false);
        } else {


            var str=banTxt;
                          //Here I am using search() to find position of Special Character.
            var n=banTxt.search(/[^a-zA-Z ]/g);
            alert("position of special char is: " + n);


            var preTxt = banTxt.substring(0,(txtLength - 1));
            var preTxtLength = preTxt.length;
            alert("Special characters are not allowed!");
            if(preTxtLength == 0){
                $('#btn').attr('disabled',true);
                document.getElementById("txt").value = "";
            }else if(preTxtLength != 0){
                document.getElementById("txt").value = preTxt;
                $('#btn').attr('disabled',false);
            }
        }
    } else {
        $('#btn').attr('disabled',true);
    }
}

function isAlphaNumeric(inputString) {
    return inputString.match(/^[0-9A-Za-z]+$/);
}

function getValue(){
    var txtValue = document.getElementById("txt").value;
    alert("Value submitted is: " + txtValue);
}
 var n=banTxt.search(/[^a-zA-Z ]/g); 

我尝试使用带有特殊字符的字符串,例如123#4 $ 5,12#4等,由于特殊字符的位置为:0,我收到了警报

这就是您的正则表达式所匹配的:没有字母字符,没有空格-包括数字。 相反,您的isAlphaNumeric函数与/^[0-9A-Za-z]+$/匹配-您可能希望将它们彼此对齐。

实际上,我已经使用以下行var n = banTxt.search(/ [^ a-zA-Z] / g); 为了获得特殊字符的位置,同时请注意,我使用了onkeyup事件,因此,如果我复制粘贴代码,即先按ctrl然后按v ,按ctrl + v则按ctrl本身就是按键事件,我认为这可能是原因我将0作为特殊字符的位置,因为按Ctrl后没有粘贴任何文本,但触发了onkeyup事件。

我正在寻找解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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