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
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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.