我有一个带有文本框的页面,用户应该在其中输入一个24个字符(字母和数字,不区分大小写)的注册代码。我使用maxlength来限制用户输入24个字符。
注册代码通常是用破折号分隔的一组字符,但我希望用户输入的代码不带破折号。
我怎么能写我的JavaScript代码没有jQuery检查用户输入的给定字符串不包含破折号,或者更好的是,只包含字母数字字符?
我有一个带有文本框的页面,用户应该在其中输入一个24个字符(字母和数字,不区分大小写)的注册代码。我使用maxlength来限制用户输入24个字符。
注册代码通常是用破折号分隔的一组字符,但我希望用户输入的代码不带破折号。
我怎么能写我的JavaScript代码没有jQuery检查用户输入的给定字符串不包含破折号,或者更好的是,只包含字母数字字符?
当前回答
var inputString = "this is home"; Var findme = "home"; if (inputString.indexOf(findme) > -1) { Alert(“找到了”); }其他{ Alert(“未找到”); }
其他回答
includes()方法确定数组在其条目中是否包含某个值,根据需要返回true或false。
const array1 = [1, 2, 3];
console.log(array1.includes(2));
// expected output: true
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
// expected output: true
console.log(pets.includes('at'));
// expected output: false
知道更多
凯文的答案是正确的,但它需要一个“神奇”的数字如下:
var containsChar = s.indexOf(somechar) !== -1;
在这种情况下,您需要知道-1代表未找到。 我认为更好的说法应该是:
var containsChar = s.indexOf(somechar) >= 0;
使用ES6 MDN docs .includes()
"FooBar".includes("oo"); // true
"FooBar".includes("foo"); // false
"FooBar".includes("oo", 2); // false
E: IE不支持-相反,你可以使用波浪号操作符~(按位Not)和.indexOf()
~"FooBar".indexOf("oo"); // -2 -> true
~"FooBar".indexOf("foo"); // 0 -> false
~"FooBar".indexOf("oo", 2); // 0 -> false
与数字一起使用,波浪符有效 ~ n => -(n +1)。用双重否定!!(逻辑不)转换bool中的数字:
!!~"FooBar".indexOf("oo"); // true
!!~"FooBar".indexOf("foo"); // false
!!~"FooBar".indexOf("oo", 2); // false
使用正则表达式来实现这一点。
function isAlphanumeric( str ) {
return /^[0-9a-zA-Z]+$/.test(str);
}
演示:include()方法在整个字符串中查找“contains”字符,它将返回true。
var string = "这是一个tutsmake.com,本教程包含javascript include()方法的例子。" str.includes(“包含”); // this的输出 真正的