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.
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.
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.
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
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
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" ) );