我有一个带有文本框的页面,用户应该在其中输入一个24个字符(字母和数字,不区分大小写)的注册代码。我使用maxlength来限制用户输入24个字符。
注册代码通常是用破折号分隔的一组字符,但我希望用户输入的代码不带破折号。
我怎么能写我的JavaScript代码没有jQuery检查用户输入的给定字符串不包含破折号,或者更好的是,只包含字母数字字符?
我有一个带有文本框的页面,用户应该在其中输入一个24个字符(字母和数字,不区分大小写)的注册代码。我使用maxlength来限制用户输入24个字符。
注册代码通常是用破折号分隔的一组字符,但我希望用户输入的代码不带破折号。
我怎么能写我的JavaScript代码没有jQuery检查用户输入的给定字符串不包含破折号,或者更好的是,只包含字母数字字符?
当前回答
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 string1 = "Hi Stack Overflow. I like to eat pizza."
var string2 = "Damn, I fail."
var regex = /(pizza)/g // Insert whatever phrase or character you want to find
string1.test(regex); // => true
string2.test(regex); // => false
在5分钟内学会正则表达式?
一个regex模式测试示例,你可以用它来找出字符串是否包含字符'@':
/(@[A-Za-z])\w+/.test(str_text)
凯文的答案是正确的,但它需要一个“神奇”的数字如下:
var containsChar = s.indexOf(somechar) !== -1;
在这种情况下,您需要知道-1代表未找到。 我认为更好的说法应该是:
var containsChar = s.indexOf(somechar) >= 0;
例如,如果要从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();
}
});
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
知道更多