0

I basically want to parse a string such as:

"#FFFFFF"   to "#FFFFFF",
"##FFFFFF"  to "#FFFFFF",
"FFFFFF"    to "#FFFFFF"

I'm having issues making a generic regex expression that will handle cases like this. Any help would be appreciated.

1
  • wow - so many insanely complex solutions to this... Commented Aug 10, 2012 at 18:46

8 Answers 8

3
var str =  '###FFFF';
str = str.replace (/^#*/, '#')

Replaces 0 or more occurrences of # at the start of the string with a single #

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

Comments

1

You want something like /^[#][^#]*$/

Comments

1
var string = "#fffff";
string = string.replace(/#*/g, function(m, i){ return !i?"#":"";});

Comments

1

I would replace any (or none) of the # characters at the beginning with a single instance of #:

resultString = sourceString.replace(/^#*/, "#");

Comments

1
function formatThing(string){
    return "#" + string.replace(/#/g,"");
}

Replace all '#' with nothing, and stick a '#' on the front. In my opinion this is more readable than any convoluted regex. It works for all three of the inputs provided, as well as a few other odd cases.

Mind you, this is for converting as your question suggested you wanted, not matching. Better if you're trying to normalize different inputs, in that X to Y sense you wrote in the question. Taking "##FFFFFF" and matching all except the first "#", or refusing to match "FFFFFF" because it lacks a leading "#" wouldn't suffice here right off the bat.

Comments

1

You will want to match any number of # OR then anything in the beginning. Like so (see jsFiddle):

new RegExp("(^#+|^)");

// #Test -> #Test
// ####Test -> #Test
// Test -> #Test

2 Comments

Just FYI, you don't need the "g" modifier.
True, there should only ever be one of these since he wants it starting at the beginning of the string. I'm fixing the code.
0

This will not validate that the string is in fact a valid color, but just enforce that the string has exactly one hash as the first character (by stripping all hashes from the string no matter where they are and then adding one at the front):

var colorString = "##ffffff";

console.log("#" + colorString.replace(/#/g, "")); // prints #ffffff

Comments

0

Another solution to add to the mix that checks for a 3-6 letter hex code with or without a leading #.

var re = /#?([A-F0-9]{3,6})/i;
function getHex (str){
   var val = str.match(re)
   return val ? "#" + val[1] : null;
}

console.log( getHex( "#FFFFFF" ) ); 
console.log( getHex( "##FFFFFF" ) );
console.log( getHex( "FFFFFF" ) );

Comments

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.