My goal is to apply the color (whatever it may be) to a span element.
No need, you can simply use rgb(18, 115, 224)
directly as a CSS color value. (However, if necessary, see below for obtaining the hexadecimal code.) Here's an example:
$("#the-span").css("color", "rgb(18, 115, 224)");
<span id="the-span">I'm the span</span>
Alternatively, without jQuery, here's how you can do it:
document.getElementById("the-span").style.color = "rgb(18, 115, 224)";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="the-span">I'm the span</span>
However, if you really need the hex value for some reason:
function getRGB(str) {
var result = /rgb\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*\d+\s*)?\)/.exec(str);
if (result) {
return "#" +
toHex(+result[1], 2) +
toHex(+result[2], 2) +
toHex(+result[3], 2);
}
return undefined;
}
// Note that this is a basic toHex function only suitable for this purpose
function toHex(num, min) {
var hex = num.toString(16);
while (hex.length < (min || 0)) {
hex = "0" + hex;
}
return hex;
}
function test(str) {
display(str + " => " + getRGB(str));
}
test("rgb(18, 115, 224)");
test("rgb(18, 115, 224, 50)");
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
This function accounts for the possibility of a fourth (alpha) argument, even though we don't utilize it in this case.