在Javascript Regex中,如何验证字符串是否为有效的十六进制颜色?

时间:2022-09-13 11:15:33

Given a string like #fff443 or #999999

给出像#fff443或#999999这样的字符串

How do I verify that the string has:

如何验证字符串是否包含:

  • 7 characters, with the first one being a hash
  • 7个字符,第一个是哈希
  • no symbols in the string besides the hash in the beginning
  • 除了开头的哈希之外,字符串中没有符号

1 个解决方案

#1


18  

It seems that you are matching against a css color:

看来你匹配css颜色:

function isValidColor(str) {
    return str.match(/^#[a-f0-9]{6}$/i) !== null;
}

To elaborate:

详细说明:

^ match beginning
# a hash
[a-f0-9] any letter from a-f and 0-9
{6} the previous group appears exactly 6 times
$ match end
i ignore case

^匹配开始#a hash [a-f0-9]来自a-f的任何字母和0-9 {6}前一组恰好出现6次$ match end i ignore case

#1


18  

It seems that you are matching against a css color:

看来你匹配css颜色:

function isValidColor(str) {
    return str.match(/^#[a-f0-9]{6}$/i) !== null;
}

To elaborate:

详细说明:

^ match beginning
# a hash
[a-f0-9] any letter from a-f and 0-9
{6} the previous group appears exactly 6 times
$ match end
i ignore case

^匹配开始#a hash [a-f0-9]来自a-f的任何字母和0-9 {6}前一组恰好出现6次$ match end i ignore case