简体   繁体   English

检查确切的子字符串是否在字符串中

[英]Check if exact substring is in a string

I know that somewhere someone asked this question before but I've tried to find an answer without any luck. 我知道以前有人问过这个问题,但是我一直试图找到一个没有任何运气的答案。

I'm trying to find if an exact substring is found in a string. 我正在尝试查找是否在字符串中找到了确切的子字符串。

For example 例如

<input class="form-control alphanumeric-chars" />

I want to match 'alphanumeric-characters' but if the class name was alphanumeric it won't be a match 我想匹配“字母数字字符”,但是如果类名是字母数字,则不会匹配

I've tried many options like: 我尝试了很多选择,例如:

$('input').filter(function() {
   return $(this).className.includes('alphanumeric-chars');
})

Or 要么

return $(this).className === 'alphanumeric-chars';

Any idea what am I missing? 知道我想念什么吗?

There is no need of filter . 不需要filter Just use the class selector as follow 只需使用类选择器,如下所示

$('input.alphanumeric-chars')

why don't you go for hasClass() if you want to do something based on condition! 如果您想根据条件进行某些操作,为什么不选择hasClass()

if($(this).hasClass('className')){
  //do some code.
}
else{
  //do else part
}

You have multiple options if you use jquery : 如果使用jquery,则有多种选择:

$(this).hasClass('alphanumeric-chars')

or if you don't use jquery : 或者,如果您不使用jquery:

this.className.indexOf('alphanumeric-chars') // return -1 if not found, >= 0 if found

If you want all input without 'alphanumeric-chars' class you can do this : 如果您希望所有输入都没有'alphanumeric-chars'类,则可以执行以下操作:

$('input:not(.alphanumeric-chars)')

There multiple ways to find the class 有多种查找课程的方法

  1. $('input.alphanumeric-chars') // select only those input who has class name "alphanumeric-chars" $('input.alphanumeric-chars') //仅选择那些具有类名称“ alphanumeric-chars”的输入

  2. $('.alphanumeric-chars') // select all element has class name "alphanumeric-chars" $('.alphanumeric-chars') //选择所有具有类名称“ alphanumeric-chars”的元素

  3. $('[class="alphanumeric-chars"]') // select all element has class name "alphanumeric-chars" $('[class="alphanumeric-chars"]') //选择所有具有类名称“ alphanumeric-chars”的元素

  4. $('input[class="alphanumeric-chars"]') // select only those input who has class name "alphanumeric-chars" $('input[class="alphanumeric-chars"]') //仅选择那些具有类名称“ alphanumeric-chars”的输入

  5. $('input').hasClass('alphanumeric-chars') // select only those input who has class name "alphanumeric-chars" $('input').hasClass('alphanumeric-chars') //仅选择类名称为“ alphanumeric-chars”的输入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM