我有一个带有文本框的页面,用户应该在其中输入一个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

数值正则表达式


如果你在变量foo中有文本:

if (! /^[a-zA-Z0-9]+$/.test(foo)) {
    // Validation failed
}

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


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

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

仅测试字母数字字符:

if (/^[0-9A-Za-z]+$/.test(yourString))
{
    //there are only alphanumeric characters
}
else
{
    //it contains other characters
}

正则表达式正在测试0-9、A-Z和A-Z字符集中的一个或多个(+),从输入的开始(^)开始,到输入的结束($)结束。


检查字符串(单词/句子…)是否包含特定的单词/字符

if ( "write something here".indexOf("write som") > -1 )  { alert( "found it" );  } 

完美的工作。这个例子会很有帮助。

<script>    
    function check()
    {
       var val = frm1.uname.value;
       //alert(val);
       if (val.indexOf("@") > 0)
       {
          alert ("email");
          document.getElementById('isEmail1').value = true;
          //alert( document.getElementById('isEmail1').value);
       }else {
          alert("usernam");
          document.getElementById('isEmail1').value = false;
          //alert( document.getElementById('isEmail1').value);
       }
    }
</script>

<body>
    <h1>My form </h1>
    <form action="v1.0/user/login" method="post" id = "frm1">
        <p>
            UserName : <input type="text" id = "uname" name="username" />
        </p>
        <p>
            Password : <input type="text" name="password" />
        </p>
        <p>
            <input type="hidden" class="email" id = "isEmail1" name = "isEmail"/>
        </p>
        <input type="submit" id = "submit" value="Add User" onclick="return check();"/>
    </form>
</body>

试试这个:

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/


你们都想得太多了。只需使用一个简单的正则表达式,它是你最好的朋友。

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分钟内学会正则表达式?


var inputString = "this is home"; Var findme = "home"; if (inputString.indexOf(findme) > -1) { Alert(“找到了”); }其他{ Alert(“未找到”); }


String的搜索函数也很有用。它搜索给定字符串中的字符和sub_string。

'apple'.search('pl')返回2

'apple'.search('x')返回-1


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

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

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

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

使用ES6 MDN docs .includes()

"FooBar".includes("oo"); // true

"FooBar".includes("foo"); // false

"FooBar".includes("oo", 2); // false

E: IE不支持-相反,你可以使用波浪号操作符~(按位Not)和.indexOf()

~"FooBar".indexOf("oo"); // -2 -> true

~"FooBar".indexOf("foo"); // 0 -> false

~"FooBar".indexOf("oo", 2); // 0 -> false

与数字一起使用,波浪符有效 ~ n => -(n +1)。用双重否定!!(逻辑不)转换bool中的数字:

!!~"FooBar".indexOf("oo"); // true

!!~"FooBar".indexOf("foo"); // false

!!~"FooBar".indexOf("oo", 2); // false

 

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) ! } }; }


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

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

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

演示:include()方法在整个字符串中查找“contains”字符,它将返回true。

var string = "这是一个tutsmake.com,本教程包含javascript include()方法的例子。" str.includes(“包含”); // this的输出 真正的


检查字符串是否为字母数字或字母数字+一些允许的字符

最快的字母数字方法可能是如上所述:在Javascript中字母数字检查的最佳方法,因为它直接操作数字范围。

然后,为了允许其他一些额外的字符,我们可以把它们放在一个Set中进行快速查找。

我相信这个实现将正确地处理代理对。

#!/usr/bin/env node

const assert = require('assert');

const char_is_alphanumeric = function(c) {
  let code = c.codePointAt(0);
  return (
    // 0-9
    (code > 47 && code < 58) ||
    // A-Z
    (code > 64 && code < 91) ||
    // a-z
    (code > 96 && code < 123)
  )
}

const is_alphanumeric = function (str) {
  for (let c of str) {
    if (!char_is_alphanumeric(c)) {
      return false;
    }
  }
  return true;
};

// Arbitrarily defined as alphanumeric or '-' or '_'.
const is_almost_alphanumeric = function (str) {
  for (let c of str) {
    if (
      !char_is_alphanumeric(c) &&
      !is_almost_alphanumeric.almost_chars.has(c)
    ) {
      return false;
    }
  }
  return true;
};
is_almost_alphanumeric.almost_chars = new Set(['-', '_']);

assert( is_alphanumeric('aB0'));
assert(!is_alphanumeric('aB0_-'));
assert(!is_alphanumeric('aB0_-*'));
assert(!is_alphanumeric('你好'));

assert( is_almost_alphanumeric('aB0'));
assert( is_almost_alphanumeric('aB0_-'));
assert(!is_almost_alphanumeric('aB0_-*'));
assert(!is_almost_alphanumeric('你好'));

GitHub上游。

在Node.js v10.15.1中测试。


这对我很有效!

属性包含选择器[name*= " value "]

这是针对值匹配的最慷慨的jQuery属性选择器。如果选择器的字符串出现在元素的属性值内,它将选择一个元素。将此选择器与Attribute Contains Word选择器进行比较(例如[attr~=" Word "]),后者在许多情况下更合适。

来源:Attribute Contains Selector [name*= " value "] => https://api.jquery.com/attribute-contains-selector/

 <!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>attributeContains demo</title>
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
 
<input name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">
 
<script>
$( "input[name*='man']" ).val( "has man in it!" );
</script>
 
</body>
</html>

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

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


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

知道更多


你可以使用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 >