[英]replace Regular Expression by a modified version of the Regular Expression result
So I am trying to locate and replace all the color values of a css by a modified version of themselves. 因此,我试图通过自身的修改版本来查找和替换css的所有颜色值。 In this case, I am concentrating on all color codes with the same values. 在这种情况下,我将专注于所有具有相同值的颜色代码。
Replace #333333 by #333. 将#333333替换为#333。
My code is the following: 我的代码如下:
var regex = textCssMini1.replace(/\#\d{6}/g,"$1");
My code allows me to locate the #333333 and replaces it by $1. 我的代码允许我定位#333333并将其替换为$ 1。 However I want to replace it by #333. 但是我想用#333代替它。
NB: Multiple instances of color codes exist in my string such as #000000, thus I want to apply it to any possibility. 注意:我的字符串中存在多个颜色代码实例,例如#000000,因此我想将其应用于任何可能性。
You can use following regex with capturing group replace(/#([\\da-f])\\1([\\da-f])\\2([\\da-f])\\3/ig, "#$1$2$3")
您可以使用以下正则表达式捕获组replace(/#([\\da-f])\\1([\\da-f])\\2([\\da-f])\\3/ig, "#$1$2$3")
var textCssMini1 = '#111111 #123456 #ffffff #225588 #235588 #333333 #gggggg ( not valid color code )'; var regex = textCssMini1.replace(/#([\\da-f])\\1([\\da-f])\\2([\\da-f])\\3/ig, "#$1$2$3"); document.write(regex);
这个var regex = textCssMini1.replace(/\\#(\\d){6}/g,"#$1$1$1");
怎么样var regex = textCssMini1.replace(/\\#(\\d){6}/g,"#$1$1$1");
This will work 这会起作用
var regex = textCssMini1.replace(/#([\da-f])\1{5}/ig,"#$1$1$1");
JS Demo JS演示
var textCssMini1 = '#111111 #123456 #ffffff'; var regex = textCssMini1.replace(/#([\\da-f])\\1{5}/ig,"#$1$1$1"); document.write(regex);
If you want to replace each RGB
values separately 如果要分别替换每个RGB
值
var regex = textCssMini1.replace(/#([\da-f])\1([\da-f])\2([\da-f])\3/ig,"#$1$2$3");
This should by what you need: 这应该根据您的需要:
var regex = textCssMini1.replace(/\#(.)\1(.)\2(.)\3/i,"#$1$2$3");
Matches only if the is a string with a # char followed by 3 sequence of 2 identical characters, and if matches get replaced by a char followed by the 3 sigle characters. 仅当the是具有#char的字符串,后跟3个2个相同字符的序列,并且匹配项被char替换,后跟3个单字符时,才匹配。
Test: 测试:
var tomin =document.querySelector('#tominify').innerHTML; var minified = tomin.replace(/\\#(.)\\1(.)\\2(.)\\3/ig,"#$1$2$3"); document.querySelector('#minicolor').innerHTML=minified;
Sample css to test regex minify colors: <p id="tominify"> test1 { color: #442299; background-color: #442279; } test2 { color: #333333; background-color: #111112; } </p> <p id='minicolor'> </p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.