如何判断字符串是否包含JavaScript中的特定字符?

如何判断字符串是否包含JavaScript中的特定字符?,javascript,string,Javascript,String,我有一个带有文本框的页面,用户应该在其中输入24个字符(字母和数字,不区分大小写)的注册码。我使用了maxlength来限制用户输入24个字符 注册码通常以破折号分隔的字符组形式给出,但我希望用户输入代码时不要使用破折号 在没有jQuery的情况下,如何编写JavaScript代码来检查用户输入的给定字符串是否不包含破折号,或者更好的是,是否只包含字母数字字符?在您的字符串中查找“hello” if (your_string.indexOf('hello') > -1) { alert

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

注册码通常以破折号分隔的字符组形式给出,但我希望用户输入代码时不要使用破折号

在没有jQuery的情况下,如何编写JavaScript代码来检查用户输入的给定字符串是否不包含破折号,或者更好的是,是否只包含字母数字字符?

您的字符串中查找“hello”

if (your_string.indexOf('hello') > -1)
{
  alert("hello found inside your_string");
}
对于字母数字,可以使用正则表达式:


如果变量
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中的1个或多个(+),从输入的开头(^)开始,到输入的结尾($)结束。检查字符串(单词/句子…)是否包含特定的单词/字符

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>

函数检查()
{
var val=frm1.uname.value;
//警报(val);
如果(val.indexOf(“@”)>0)
{
警报(“电子邮件”);
document.getElementById('isEmail1')。value=true;
//警报(document.getElementById('isEmail1').value);
}否则{
警报(“用户名称”);
document.getElementById('isEmail1')。value=false;
//警报(document.getElementById('isEmail1').value);
}
}
我的表格

用户名:

密码:

试试这个:

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'!");

这里有一个例子:

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

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

var inputString=“这是家”;
var findme=“主页”;
if(inputString.indexOf(findme)>-1){
警惕(“发现它”);
}否则{
警报(“未找到”);

}
字符串的搜索功能也很有用。它搜索给定字符串中的字符和子字符串

'apple'。搜索('pl')
返回
2


'apple'。搜索('x')
返回
-1

Kevins的答案是正确的,但它需要一个“魔法”数字,如下所示:

var containsChar = s.indexOf(somechar) !== -1;
在这种情况下,您需要知道-1表示未找到。 我认为更好的版本是:

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


E:不受IE支持-相反,你可以使用Tilde Operator
~
()和

与数字一起使用时,波浪线操作符不起作用
~N=>-(N+1)
。与双重否定一起使用
()以转换布尔值中的数字:

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

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

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

 

ES6在字符串的
原型中包含内置方法(),该方法可用于检查字符串是否包含其他字符串

var str='生存还是毁灭,这是个问题';

console.log(str.includes('To be'))如果要搜索字符串开头或结尾的字符,也可以使用
startsWith
endsWith

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

例如,如果您正在从DOM读取数据,例如p或h1标记,那么您将需要使用两个本机JavaScript函数,这非常简单,但仅限于es6,至少对于我将要提供的解决方案来说是如此。我将搜索DOM中的所有p标记,如果文本包含“T”,则整个段落将被删除。我希望这个小例子能帮助别人

HTML

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

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

true
检查字符串是字母数字还是字母数字+一些允许的字符

最快的字母数字方法可能如中所述:因为它直接作用于数字范围

然后,为了合理地允许一些额外的字符,我们可以将它们放在快速查找中

我相信这一实施将正确处理

#!/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('你好'));
#/usr/bin/env节点
const assert=require('assert');
常量字符是字母数字=函数(c){
设code=c.codePointAt(0);
返回(
// 0-9
(代码>47&&代码<58)||
//A-Z
(代码>64&&代码<91)||
//a-z
(代码>96&&代码<123)
)
}
常量是字母数字=函数(str){
for(让c代表str){
如果(!char_是字母数字(c)){
返回false;
}
}
返回true;
};
//任意定义为字母数字或“-”或“-”。
常量几乎是字母数字=函数(str){
for(让c代表str){
如果(
!char_是字母数字(c)&&
!几乎是字母数字。几乎是字符has(c)
) {
返回false;
}
}
返回true;
};
几乎是字母数字。几乎是字符=新集合(['-','''']);
断言(是字母数字('aB0');
断言(!是字母数字('aB0_-');
断言(!is_字母数字('aB0_-*'));
断言(!是字母数字('你好'));
断言(几乎是字母数字('aB0');
断言(几乎是字母数字('aB0');
断言(!几乎是字母数字('aB0 \-*');
断言(!几乎是字母数字('你好'));

在Node.js v10.15.1中测试。

对我来说很有用! 属性包含选择器[名称*=“值”] 这是与值匹配的最慷慨的jQuery属性选择器。如果选择器的字符串出现在元素属性值中的任何位置,它将选择元素。将此选择器与包含单词选择器的属性进行比较(例如[attr~=“Word”]),这更接近
const country = "pakistan";
country.startsWith('p'); // true
country.endsWith('n');  // true
<p>Text you need to read one</p>
<p>Text you need to read two</p>
<p>Text you need to read three</p>
let paras = document.querySelectorAll('p');

paras.forEach(p => {
  if(p.textContent.includes('T')){
       p.remove();
    } 
});
#!/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('你好'));
 <!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>