简体   繁体   中英

javascript, regexp - wrap color values in span

I want all the CSS color values in my <code> element to be wrapped in span tags.

So this:

<code id="colorful-css">
body {
    color: black;
}
a {
    text-decoration: none;
    color: #0cf;
}
#box {
    outline: 1px solid rgb(255,0,0);
    background: hsla(235, 85%, 43%,.5);
}
</code>

would become this:

<code id="colorful-css">
body {
    color: <span class="css-color">black</span>;
}
a {
    text-decoration: none;
    color: <span class="css-color">#0cf</span>;
}
#box {
    outline: 1px solid <span class="css-color">rgb(255,0,0)</span>;
    background: <span class="css-color">hsla(235, 85%, 43%,.5)</span>;
}
</code>

Thanks for your help!

If you are not going to parse CSS fully and thus don't mind some possible mistakes (comments, quotes, etc), you could use an expression like:

#(?:[\da-f]{3}){1,2}\b|\b(?:rgba?|hsla?)\([^()]+\)|\b(?:red|blue|list|of|valid|color|names|...)\b

Expanded as needed.

You need a syntax highlighter for that. I'm not an expert at coding but you could use some plugin like Google Code Prettify

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM