Dan*_*don 304 javascript string
我有一个带有文本框的页面,用户应输入24个字符(字母和数字,不区分大小写)注册码.我曾经maxlength限制用户输入24个字符.
注册码通常以短划线分隔的字符组给出,但我希望用户输入没有短划线的代码.
如何在没有jQuery的情况下编写我的JavaScript代码来检查用户输入的给定字符串是否包含破折号,或者更好的是,只包含字母数字字符?
kem*_*002 556
在...找到"你好" your_string
if (your_string.indexOf('hello') > -1)
{
  alert("hello found inside your_string");
}
对于字母数字,您可以使用正则表达式:
http://www.regular-expressions.info/javascript.html
jul*_*bor 59
使用ES6 .includes()
"FooBar".includes("oo"); // true
"FooBar".includes("foo"); // false
"FooBar".includes("oo", 2); // false
E:没有被IE支持 - 相反,你可以使用Tilde opperator ~(Bitwise NOT)和.indexOf()
~"FooBar".indexOf("oo"); // -2 -> true
~"FooBar".indexOf("foo"); // 0 -> false
~"FooBar".indexOf("oo", 2); // 0 -> false
与数字一起使用,Tilde运算符有效
 ~N => -(N+1).使用双重否定!!(逻辑非)来转换bools中的数字:
!!~"FooBar".indexOf("oo"); // true
!!~"FooBar".indexOf("foo"); // false
!!~"FooBar".indexOf("oo", 2); // false
cdh*_*wie 49
如果你有变量中的文字foo:
if (! /^[a-zA-Z0-9]+$/.test(foo)) {
    // Validation failed
}
这将测试并确保用户输入了至少一个字符,并且仅输入了字母数字字符.
T.T*_*dua 18
检查字符串(单词/句子...)是否包含特定的单词/字符
if ( "write something here".indexOf("write som") > -1 )  { alert( "found it" );  } 
ES6includes在String中包含内置方法()prototype,可用于检查字符串是否包含另一个字符串.
var str = 'To be, or not to be, that is the question.';
console.log(str.includes('To be')); 以下polyfill可用于在不支持的浏览器中添加此方法.(来源)
if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';
    if (typeof start !== 'number') {
      start = 0;
    }
    
    if (start + search.length > this.length) {
      return false;
    } else {
      return this.indexOf(search, start) !== -1;
    }
  };
}使用正则表达式来完成此任务.
function isAlphanumeric( str ) {
 return /^[0-9a-zA-Z]+$/.test(str);
}
你们都在想太多.只需使用简单的正则表达式,它就是你最好的朋友.
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
如果您在字符串的开头或结尾搜索字符,您还可以使用startsWith和endsWith 
const country = "pakistan";
country.startsWith('p'); // true
country.endsWith('n');  // true
仅测试字母数字字符:
if (/^[0-9A-Za-z]+$/.test(yourString))
{
    //there are only alphanumeric characters
}
else
{
    //it contains other characters
}
正则表达式正在测试字符集 0-9、AZ 和 az 中的 1 个或多个 (+),从输入的开头 (^) 开始,到输入的结尾 ($) 结束。
var inputString = "this is home";
var findme = "home";
if ( inputString.indexOf(findme) > -1 ) {
    alert( "found it" );
} else {
    alert( "not found" );
}小智 5
凯文斯的回答是正确的,但它需要一个“魔术”数字,如下所示:
var containsChar = s.indexOf(somechar) !== -1;
在这种情况下,您需要知道-1代表not found。我认为更好的版本是:
var containsChar = s.indexOf(somechar) >= 0;
您可以使用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 = "found '" + include + "' in your string";
}<p id="a"></p>| 归档时间: | 
 | 
| 查看次数: | 662208 次 | 
| 最近记录: |