Javascript通配符变量



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

我想检查一下,除了第三个和第四个字符外,其他字符是否都相同。

类似于:

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

如何使用JavaScript实现这一点?

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

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

使用正则表达式匹配:

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

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

if (/GB..NTQQ/.test(product_id)) {
  ...
}
 if (myString.match(/regex/)) { /*Success!*/ }

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

最新更新