问题描述:

So I am trying to locate and replace all the color values of a css by a modified version of themselves. In this case, I am concentrating on all color codes with the same values.

Replace #333333 by #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. However I want to replace it by #333.

NB: Multiple instances of color codes exist in my string such as #000000, thus I want to apply it to any possibility.

网友答案:

You can use following regex with capturing group 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);
网友答案:

how about this 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

var textCssMini1 = '#111111 #123456 #ffffff';
var regex = textCssMini1.replace(/#([\da-f])\1{5}/ig,"#$1$1$1");
document.write(regex);
网友答案:

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.

  • #225588 > #258 (replaced)
  • #235588 > #235588 (not replaced)
  • #333333 > #333 (replaced)

    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>
  • 相关阅读:
    Top