Elon Salfati
Elon Salfati

Reputation: 1687

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?

Upvotes: 0

Views: 226

Answers (4)

Satish Kumar sonker
Satish Kumar sonker

Reputation: 1288

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"

Upvotes: 0

ekans
ekans

Reputation: 1724

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)')

Upvotes: 0

RaJesh RiJo
RaJesh RiJo

Reputation: 4400

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
}

Upvotes: 1

Tushar
Tushar

Reputation: 87233

There is no need of filter. Just use the class selector as follow

$('input.alphanumeric-chars')

Upvotes: 2

Related Questions