*
将 rgb 颜色字符串转换为十六进制的形式,如 rgb(255, 255, 255) 转为 #ffffff
1. rgb 中每个 , 后面的空格数量不固定
2. 十六进制表达式使用六位小写字母
3. 如果输入不符合 rgb 格式,返回原始输入
input: ‘rgb(255, 255, 255)‘
output: #ffffff
function rgb2hex(sRGB) {var int2hex = function(n, w) {var m, s = [], c;w = w || 2;while (n) {m = n % 16;if (10 <= m) {c = String.fromCharCode(97+m-10);} else {c = "" + m;}s.unshift(c);n = Math.floor(n/16);}var p = w-s.length; // length to pad ‘0‘while (p--) {s.unshift(‘0‘);}return s.join(‘‘);};/*var trim = function(s) {return s.replace(/(^\s*)|(\s*$)/g, "");};*/ ???return sRGB.replace(/^rgb\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\)$/, ????function($0, $1, $2, $3) { ???return ‘#‘ +int2hex($1) + int2hex($2) + int2hex($3); ???});}console.log(rgb2hex(‘rgb(255, 255, 255)‘)); ?// #ffffffconsole.log(rgb2hex(‘rgb(90, 103, 111)‘)); ?// #5a676fconsole.log(rgb2hex(‘rgb(0,0,15)‘)); ??// #00000f// 10进制整数 转化为16进制 2位
// (‘0‘+(+str).toString(16)).slice(-2)
function rgb2hex(sRGB) {var int2hex = function(str) {return (‘0‘+(+str).toString(16)).slice(-2);}; ???return sRGB.replace(/^rgb\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\)$/, ????function($0, $1, $2, $3) { ???return ‘#‘ +int2hex($1) + int2hex($2) + int2hex($3); ???});}
* 字符串转化为驼峰形式
css 中经常有类似 background-image 这种通过 - 连接的字符,通过 javascript 设置样式的时候需要将这种样式转换成 backgroundImage 驼峰格式,请完成此转换功能
1. 以 - 为分隔符,将第二个起的非空单词首字母转为大写
2. -webkit-border-image 转换后的结果为 webkitBorderImage
function cssStyle2DomStyle(sName) { ???var ucfirst = function(s, delim) { ???????delim = delim || ‘-‘; ???????return s.split(delim).map(function(s) { ???????????var c = s.charCodeAt(0); ???????????if (65 <= c && c < 65 + 26) { ???????????????return s; ???????????} ???????????if (97 <= c && c < 97 + 26) { ???????????????c = c & 0xdf; ???????????} ???????????return String.fromCharCode(c) + s.substr(1); ???????}).join(‘‘); ???} ???var lowerFirstLetter = function(s) { ???????var i = 0, ???????????c = s.charCodeAt(i); ???????while (i < s.length) { ???????????if (97 <= c && c < 97 + 26) { ???????????????return s; ???????????} ???????????if (65 <= c && c < 65 + 26) { ???????????????c = c | 0x20; ???????????????break; ???????????} else { ???????????????c = s.charCodeAt(++i); ???????????} ???????} ???????return String.fromCharCode(c) + s.substr(i+1); ???} ???var s = ucfirst(sName); ???return lowerFirstLetter(s);}console.log(cssStyle2DomStyle("-webkit-border-image")); // webkitBorderImageconsole.log(cssStyle2DomStyle("font-size")); // fontSizeconsole.log(cssStyle2DomStyle("--selection")); // selection/ / RegExp
// 链接:https://www.nowcoder.com/questionTerminal/2ded24e34ec34325a62d42d0c8479bae// 来源:牛客网function cssStyle2DomStyle(sName) { return sName.replace(/(?!^)\-(\w)(\w+)/g, function(a, b, c){ return b.toUpperCase() + c.toLowerCase(); }).replace(/^\-/, ‘‘);}
css颜色字符串转换, 字符串转化为驼峰形式
原文地址:https://www.cnblogs.com/mingzhanghui/p/9251634.html