【问题标题】:Javascript wildcard variable?Javascript通配符变量?
【发布时间】:2012-02-13 19:27:23
【问题描述】:

product_id 的值可能是一些字母和数字的组合,例如:GB47NTQQ。

我想检查除第 3 和第 4 个字符之外的所有字符是否相同。

类似:

if product_id = GBxxNTQQ //where x could be any number or letter.
    //do things
else
    //do other things

我怎样才能用 JavaScript 做到这一点?

【问题讨论】:

    标签: javascript variables wildcard


    【解决方案1】:

    使用正则表达式和 string.match()。句点是单个通配符。

    string.match(/GB..NTQQ/);
    

    【讨论】:

    • 这篇文章很旧,但我建议使用/GB\w\wNTQQ/,因为 OP 正在寻找字母和数字。 \w 匹配字母数字和下划线。要排除下划线并仅使用字母数字,您可以这样做:/GB[a-zA-Z0-9]{2}NTQQ/
    【解决方案2】:

    使用regular expression 匹配:

    if ('GB47NTQQ'.match(/^GB..NTQQ$/)) {
        // yes, matches
    }
    

    【讨论】:

    • javascript 中的正则表达式,非常好:) +1
    【解决方案3】:
     if (myString.match(/regex/)) { /*Success!*/ }
    

    您可以在这里找到更多信息:http://www.regular-expressions.info/javascript.html

    【讨论】:

      【解决方案4】:

      到目前为止的答案建议match,但test 可能更合适,因为它返回truefalse,而match 返回null 或匹配数组,因此需要对条件内的结果进行(隐式)类型转换。

      if (/GB..NTQQ/.test(product_id)) {
        ...
      }
      

      【讨论】:

      • 它并没有真的有很大的不同,但是是的,你是对的...... +1 :)
      猜你喜欢
      • 1970-01-01
      • 2017-04-20
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      相关资源
      最近更新 更多