jQuery:检查字符是否在字符串中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3139477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:54:29  来源:igfitidea点击:

jQuery: Check if character is in string

jqueryvariables

提问by Jonathan

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

我想要最简单的方法来检查下划线 (_) 是否在使用 jQuery 的变量中,如果不是,则执行某些操作。

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

Thanks!

谢谢!

回答by Reigel

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.. indexOfis a native javascript

正如下面的支出者在评论中所说的那样,jQuery 不是必需的…… indexOf是原生 javascript

回答by Nishad Up

There is some more 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. with regular expression

    if( str.match(/_/g) ).length{
      //Do something
    }
    else{
      //Do something
    }
    
  1. indexOf() 方法。

    if( str.indexOf('_') != -1 ){
       //do something
    }
    else{
       //do something 
    } 
    
  2. 搜索()方法。

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

    if( $("p:contains(_)") ).length{
      //Do something
    }
    else{
      //Do something
    }
    
  4. 使用正则表达式

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

I Think the simplest way is first method.

我认为最简单的方法是第一种方法。