简体   繁体   中英

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 . 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!

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

You have multiple options if you use jquery :

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

or if you don't use 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 :

$('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"

  2. $('.alphanumeric-chars') // select all element has class name "alphanumeric-chars"

  3. $('[class="alphanumeric-chars"]') // select all element has class name "alphanumeric-chars"

  4. $('input[class="alphanumeric-chars"]') // select only those input who has class name "alphanumeric-chars"

  5. $('input').hasClass('alphanumeric-chars') // select only those input who has class name "alphanumeric-chars"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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