Javascript match if变量大于5个0

Javascript match if variable has more than five zeros

本文关键字:5个 大于 变量 match if Javascript      更新时间:2023-09-26

我试图检查src是否有超过五个连续的零。例如http://domain.com/images/00000007.jpg可以匹配,但http://domain.com/images/0000_1.jpg不可以。这是我到目前为止所拥有的,但它似乎不起作用。有什么建议吗?

if (src.match(/0{5,}$/)) {
  match found
}
else {
  no match found
}

您应该从字符串的开头^匹配零,即

if (/^0{5,}/.test(src)) { ... }

如果您需要在字符串的任意位置匹配5个连续零,则省略任何^$

UPDATED:在您的情况下,您可以使用if (/'/0{5,}/.test(src)) { ... }

还可以使用indexOf(),类似如下:

if(src.indexOf('00000') > -1){
    alert('matchFound');
} else {
    alert('no match found');
}

试试这个:

/0{5,}[^'/]*$/

检查是否有5个或更多的0,后面跟着字符串末尾的斜杠以外的任何字符。如果想进行其他验证,可以使用正斜杠开始模式,以确保文件以五个零开头,或者可以在末尾添加可接受的文件类型:

/'/0{5,}[^'/]*'.(jpe?g|gif|png)$/i

一个细分(对于任何你或未来的读者不知道的部分):

/             Starts the regular expression
  '/          A literal forward slash (escaped because '/' is a delimiter)
  0{5,}       Five or more zeros
  [^'/]*      Anything except a literal forward slash, zero or more times.
  '.          A literal period (unescaped periods match anything except newlines)
  (           start a group
    jpe?g     jpeg or jpg (the ? makes the 'e' match zero or 1 times)
    |         OR
    gif       gif
    |         OR
    png       png
  )           End group
  $           Assert the end of the string.
/             End the regular expression
i             Case insensitive.