Javascript 6字符和空格检查

Javascript 6 character and space check

本文关键字:空格 检查 字符 Javascript      更新时间:2023-09-26

我想知道用户输入是否有6个字符,以及它在位置4是否有空格,或者如果它从零开始计数,我猜是5。我是java脚本的新手,觉得我想得太多了,请帮帮我!

然而,我对你的问题不太清楚,"或者我猜是5,如果它从零开始计数",但据我所知,你的问题的答案如下:

// get the user input through it id or whatever 
// CSS selector you are using
var userInput = document.querySelector('#user_input');
// on whatever event you are doing this check
// insert the following code to its handler
if (userInput.value.length === 6 && userInput.value[3] === " ") {
  // your check is true here and do whatever you want
  // return false
}

以下是检查用户输入是否有6个字符的功能:

function validateUserInput(inputNo) {
    if (inputNo.length == 6) {
        return true;
    }
    return false; 
}

以下是验证第4个字符是否为空格的功能:

function checkFourthCharacterAsSpace(inputNo) {
    var value = inputNo.charAt(3);  // index starts from 0
    if(value == ' ') {
        return true;
    }
    return false;
}

下面的函数接受输入,然后验证它是否是字符串obj,以便您能够正确处理它并执行所需的检查。

function _check_me( _input_obj )
{
    if ( typeof _input_obj  == "string" || _input_obj  instanceof String )
    {
         return ( _input_obj.length == 6 && ( _input_obj.charAt(4) == " " || _input_obj.charAt(5) == " " ) ) ? 1 : 0 ;
    }
    else return 0 ;
}

因此,您可以使用它,如下所示:

var _obj1 = "abcdef"; // returns false
var _obj2 = "abcd f"; // returns true
var _obj3 = "abc ef"; // returns true
document.write( _obj1 + " : " + _check_me( _obj1 ) + "<br>" ) ;
document.write( _obj2 + " : " + _check_me( _obj2 ) + "<br>" ) ;
document.write( _obj3 + " : " + _check_me( _obj3 ) + "<br>" ) ;

希望它能帮助和快乐的编码!

if (userinput.length === 6 && userinput.charAt(4) === " ") {
    // This is where your code goes
}

这样的东西会起作用。我使用"正则表达式"来测试您的需求。

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Test for pattern</title>
<script>
function testInput(){
   // get text input element
   var inputBox = document.getElementById("txtInput");
   var backgroundColor = "red";
   //check if the inputted text matches the regex.
   if(inputBox.value.match(/^'w{3}'s'w{2}$/g)){
       backgroundColor = "green";
       //.. or add whatever has to be done ...
   }
   inputBox.style.backgroundColor = backgroundColor;
}
</script>
</head>
<body>
    <input id="txtInput" type="text" onkeyup="testInput()">
</body>
</html>

工作示例:jsFiddle