我有一个带有文本框的页面,用户应该在其中输入一个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(“未找到”); }
其他回答
如果要搜索字符串开头或结尾的字符,还可以使用startsWith和endsWith
const country = "pakistan";
country.startsWith('p'); // true
country.endsWith('n'); // true
在your_string中查找"hello"
if (your_string.indexOf('hello') > -1)
{
alert("hello found inside your_string");
}
对于alpha数值,您可以使用正则表达式:
http://www.regular-expressions.info/javascript.html
数值正则表达式
如果你在变量foo中有文本:
if (! /^[a-zA-Z0-9]+$/.test(foo)) {
// Validation failed
}
这将测试并确保用户至少输入了一个字符,并且只输入了字母数字字符。
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) ! } }; }
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
知道更多