0

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?

2
  • Since you're using jQuery, hasClass might help. See here. Commented Sep 28, 2017 at 12:07
  • Without jQuery there's also element.classList.contains("classname") Commented Sep 28, 2017 at 12:10

4 Answers 4

2

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

$('input.alphanumeric-chars') 
Sign up to request clarification or add additional context in comments.

1 Comment

this one much better among all.+1.deleted my answer too
1

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 } 

Comments

0

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

2 Comments

Wont work for fdslajfldsaalphanumeric-charsDoYouGetThis
we are in class attribute, it would be safe enough here
0

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"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.