2

I'm uploading a css file from which I hope to log every color that is referenced.

So if the css file has {background-color:#ffffff; color:#000000;} , I hope to be able to create a list consisting of: #ffffff, #000000.

What would be the best way of doing this?
The project I am working on is on GitHub if you would like some reference: https://github.com/yeremenko/farbe

Thank you in advance for any help you might provide!

function getFileContents () {
    var reader = new FileReader();

    reader.onload = function(contents) {
        var fileContents = contents.target.result;  //Stores file contents
        var singleColor  = /*magic*/;

    };

    reader.readAsText(selectedFile);            //Gets file contents into string

};

getFileContents();

1 Answer 1

1

I'm not sure if this answers your question completely, but if you have the CSS file and you can read it's content, then you can simply parse out the colors. Just keep in mind that there are more types of color specifications inside CSS.

Examples:

  • #FFFFFF or #FFF as hexadecimal specification;

regexes: #[0-9aA-fF]{3} and #[0-9aA-fF]{6}

  • (255,255,255) or (255,255,255,1) as RGB or RGBA specification

regex: \([0-9]{1,3}( *, *)[0-9]{1,3}( *, *)[0-9]{1,3}( *, *[0-1]{1}(\.[0-9]*)?)\)

  • white as a color name specification

This might be a bit difficult - finding these would be probably easiest by forming a list of the available color names in CSS and looking for them separately.

With this in mind you can for example execute

var cssContent = cssFile.readContent(); // get the file into a String
firstPattern = "/`#[0-9aA-fF]{3}/g";
var matches = firstPattern.exec(cssContent);
while(matches!=null){
    // append to your output
}
//and so on for other patterns

Hope it helps at least a bit!

Sign up to request clarification or add additional context in comments.

4 Comments

@Sergey were you asking also about acquiring of the CSS file and reading?
Hey @dropout Thanks a lot for the help! I will try it out and get back to you but it looks great. I am able to read the file using reader.readAsText(selectedFile);
the regexes #[0-9aA-fF]{3} and #[0-9aA-fF]{6} seem to also be matching with #footer and #result. Any idea why this would happen?
@Sergey this shouldn't happen, there's no reason to match them. Try changing it to #[0-9aA-fF]{3}( *)?; and #[0-9aA-fF]{6}( *)?; that will also check if there's a semicolon after the color - IDs never have a semicolon behind them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.