26

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!

asked Jun 29, 2010 at 9:41

2 Answers 2

62
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

answered Jun 29, 2010 at 9:43
Sign up to request clarification or add additional context in comments.

2 Comments

It's probably important to highlight to OP that the solution does not require jQuery, as demonstrated.
Its worth noting that this isn't jQuery but basic javascript so could be used even without jQuery being loaded. The answer is correct of course, just a noteworthy addition given the question.
14

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.

pbarney
2,9734 gold badges41 silver badges55 bronze badges
answered Jan 22, 2016 at 9:46

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.