我有一个带有文本框的页面,用户应该在其中输入一个24个字符(字母和数字,不区分大小写)的注册代码。我使用maxlength来限制用户输入24个字符。

注册代码通常是用破折号分隔的一组字符,但我希望用户输入的代码不带破折号。

我怎么能写我的JavaScript代码没有jQuery检查用户输入的给定字符串不包含破折号,或者更好的是,只包含字母数字字符?


当前回答

在your_string中查找"hello"

if (your_string.indexOf('hello') > -1)
{
  alert("hello found inside your_string");
}

对于alpha数值,您可以使用正则表达式:

http://www.regular-expressions.info/javascript.html

数值正则表达式

其他回答

例如,如果要从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
}

这将测试并确保用户至少输入了一个字符,并且只输入了字母数字字符。

一个regex模式测试示例,你可以用它来找出字符串是否包含字符'@':

/(@[A-Za-z])\w+/.test(str_text)

在your_string中查找"hello"

if (your_string.indexOf('hello') > -1)
{
  alert("hello found inside your_string");
}

对于alpha数值,您可以使用正则表达式:

http://www.regular-expressions.info/javascript.html

数值正则表达式

使用正则表达式来实现这一点。

function isAlphanumeric( str ) {
 return /^[0-9a-zA-Z]+$/.test(str);
}