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

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

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


当前回答

ES6在String的原型中包含了内置的方法(includes),可以用来检查String是否包含另一个字符串。

var str =“生存,还是毁灭,这是一个问题。”; console.log (str。包括(','));

下面的polyfill可用于在不受支持的浏览器中添加此方法。(源)

if (!String.prototype.includes) { String.prototype.includes =函数(搜索,启动){ 使用严格的; If (typeof start !== 'number') { Start = 0; } 如果(开始+搜索。长度> this.length) { 返回错误; }其他{ 返回。indexOf(search, start) ! } }; }

其他回答

试试这个:

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/

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

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

你可以使用string.includes()。例子:

Var string = "lorem ipsum hello world"; Var include = "world"; var a = document.getElementById("a"); If (string.includes(include)) { Alert ("found '" + include + "' in your string"); a.innerHTML = " find '" + include + "' in your string"; } < p id = " " > < / p >

如果要搜索字符串开头或结尾的字符,还可以使用startsWith和endsWith

const country = "pakistan";
country.startsWith('p'); // true
country.endsWith('n');  // true

凯文的答案是正确的,但它需要一个“神奇”的数字如下:

var containsChar = s.indexOf(somechar) !== -1;

在这种情况下,您需要知道-1代表未找到。 我认为更好的说法应该是:

var containsChar = s.indexOf(somechar) >= 0;