Javascript 6字符和空格检查
Javascript 6 character and space check
我想知道用户输入是否有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
相关文章:
- 检查最后键入的字符是否为空格
- JS如何检查空字符串和空格
- 如何在Javascript中检查字符串是否包含多个空格并返回
- Javascript 6字符和空格检查
- 使用 JQuery 检查空格键的最快方法是什么
- 如何检查字符串是否有空格或结尾
- 如何在 javascript 中检查字符串开头是否有空格
- Javascript - 如何在字符串中找到子字符串并检查它之前/之后是否有空格
- JavaScript 检查回文(包括空格和标点符号)
- 如何检查字符串是否不包含任何内容或仅包含空格
- 如何在 JavaScript 中检查变量是空字符串还是空字符串或所有空格
- 正则表达式检查字符串是否仅包含字母数字字符和空格 - javascript
- JS正则表达式检查字符串的长度为字符数,介于最小值和最大值之间,不计算空格
- 使用空格键时如何检查匹配的字符串
- 检查数组中的字符串在javascript/jquery中是否有空格字符
- 如何检查javascript中只有空格的字符串
- 在JavaScript中检查字符串是否为空白(即只包含空格)的最高效方法
- 检查输入是否集中(空格键正在使用中)
- Regex检查重复的空格字符
- 如何检查输入是否只包含空格字符?即只有一个或多个空格,而没有其他字符