我有一个带有文本框的页面,用户应该在其中输入一个24个字符(字母和数字,不区分大小写)的注册代码。我使用maxlength来限制用户输入24个字符。
注册代码通常是用破折号分隔的一组字符,但我希望用户输入的代码不带破折号。
我怎么能写我的JavaScript代码没有jQuery检查用户输入的给定字符串不包含破折号,或者更好的是,只包含字母数字字符?
我有一个带有文本框的页面,用户应该在其中输入一个24个字符(字母和数字,不区分大小写)的注册代码。我使用maxlength来限制用户输入24个字符。
注册代码通常是用破折号分隔的一组字符,但我希望用户输入的代码不带破折号。
我怎么能写我的JavaScript代码没有jQuery检查用户输入的给定字符串不包含破折号,或者更好的是,只包含字母数字字符?
当前回答
试试这个:
if ('Hello, World!'.indexOf('orl') !== -1)
alert("The string 'Hello World' contains the substring 'orl'!");
else
alert("The string 'Hello World' does not contain the substring 'orl'!");
这里有一个例子:http://jsfiddle.net/oliverni/cb8xw/
其他回答
仅测试字母数字字符:
if (/^[0-9A-Za-z]+$/.test(yourString))
{
//there are only alphanumeric characters
}
else
{
//it contains other characters
}
正则表达式正在测试0-9、A-Z和A-Z字符集中的一个或多个(+),从输入的开始(^)开始,到输入的结束($)结束。
例如,如果要从DOM读取数据,例如p或h1标记,则需要使用两个原生JavaScript函数,这非常简单,但仅限于es6,至少对于我将要提供的解决方案是这样。我将搜索DOM中的所有p标签,如果文本包含“T”,整个段落将被删除。我希望这个小例子能帮助到一些人!
HTML
<p>Text you need to read one</p>
<p>Text you need to read two</p>
<p>Text you need to read three</p>
JS
let paras = document.querySelectorAll('p');
paras.forEach(p => {
if(p.textContent.includes('T')){
p.remove();
}
});
如果你在变量foo中有文本:
if (! /^[a-zA-Z0-9]+$/.test(foo)) {
// Validation failed
}
这将测试并确保用户至少输入了一个字符,并且只输入了字母数字字符。
使用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
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
知道更多