Jump to content

Matching a hexadecimal color


Guest

Recommended Posts

I have a function that prompts a user for some text and a hexadecimal color:

function bg_color(thisField) {
  var text = prompt('Enter text:', '');
  var color = prompt('Enter background color:', '#');
  while (!color.match(/\#{1}[A-Za-z0-9]{6}/)) {
    alert('Must be a hexadecimal color!');
    var color = prompt('Enter background color:', '#');
  }
  if (text != null && color != null) {
    document.thisForm.elements[thisField].value += "<bg color=\"" + color + "\">" + text + "</bg>";
  }
}

 

The problem it is seems to completely ignore the numbers in curly brackets. I can put any number of #'s in front of the number of any number of digits after the #'s and it will be just fine with it.

 

I want the function to continue asking for a hexadecimal color until it gets one # in front and 6 digits afterwards. Anyone know how to do this?

Link to comment
https://forums.phpfreaks.com/topic/226832-matching-a-hexadecimal-color/
Share on other sites

while (!color.match(/^#[A-Fa-f0-9]{6}$/)) {

 

- you don't need to escape #

- you don't need to do #{1} as it is superfluous

- hexadecimal numbers only contain letters a-f not a-z

- main thing you were missing was start  and end of string anchors (^...$) which tells the regex engine that it must start with the # followed by 6 a-f0-9 and then nothing else.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.