jonagoldman
jonagoldman

Reputation: 8754

jQuery: Check if character is in string

I want the simplest way to check if an underscore (_) is in a variable using jQuery and do something if is not..

if ( '_ is not in var') {
   // Do
}

Thanks!

Upvotes: 26

Views: 100281

Answers (2)

Nishad Up
Nishad Up

Reputation: 3615

There are several ways to do this.

  1. indexOf() method:

    if( str.indexOf('_') != -1 ){
       //do something
    }
    else{
       //do something 
    } 
    
  2. Search() method:

     if( str.search("_")!=-1 ){
       //do something
     } 
     else {
      //Do something 
     }
    
  3. :contains() selector:

     if( $("p:contains(_)") ).length{
       //Do something
     }
     else{
       //Do something
     }
    
  4. using a regular expression:

     if( str.match(/_/g) ).length{
       //Do something
     }
     else{
       //Do something
     }
    

I think the first method is the simplest way.

Upvotes: 14

Reigel Gallarde
Reigel Gallarde

Reputation: 65284

var str = "i am a string with _";
if (str.indexOf('_') == -1) {
   // will not be triggered because str has _..
}

and as spender said below on comment, jQuery is not a requirement.. indexOf is a native javascript

Upvotes: 61

Related Questions