将6位数颜色代码转换为3位数 [英] Convert 6 digit color code to 3 digits

查看:120
本文介绍了将6位数颜色代码转换为3位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果可能,我想将给定的十六进制颜色转换为3位数字.例如:

I want to convert given hex color to 3 digits if it's possible. For example:

#ffffff - #fff
#001122 - #012
#012345 - #012345

有人知道怎么做吗?

我在Google网站上找到了此正则表达式,但我不知道如何使用它们:/

I found this regex in the google webs but I don't know how to use them :/

# shorten your CSS
sed -re 's/#(([0-9a-fA-F])\2)(([0-9a-fA-F])\4)(([0-9a-fA-F])\6)/#\2\4\6/'

# expand: the three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits
sed -re 's/#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])\b/#\1\1\2\2\3\3/'

# works in egrep too
grep -E '(([0-9a-fA-F])\2)(([0-9a-fA-F])\4)(([0-9a-fA-F])\6)'

推荐答案

可能有一种更简短,更甜美的方法,但是您可以在十六进制颜色的字符之间执行简单的字符比较,并在必要时手动组装字符串,例如例如:

There's probably a shorter and sweeter way, but you could perform simple char-comparisons between the characters of the hex-color and if necessary manually assemble the string, for example:

var hex = "#aabb00";
if ((hex.charAt(1) == hex.charAt(2))
  && (hex.charAt(3) == hex.charAt(4))
  && (hex.charAt(5) == hex.charAt(6))) {
    hex = "#" + hex.charAt(1) + hex.charAt(3) + hex.charAt(5);
}

这篇关于将6位数颜色代码转换为3位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆